2016-04-27 26 views
0

後,我有按鈕,一個簡單的觸發器:WPF控件觸發採集清除設置控制背景

<Style.Triggers> 
     <Trigger Property="IsMouseOver" Value="True"> 
      <Setter Property="Background" Value="#3E6DB6"/> 
     </Trigger> 
    </Style.Triggers> 

這工作不錯,直到我設置按鈕的背景在後臺代碼:

neighborButton.Background = notClickedButtonBackground; 

在此之後neighborButton.Triggers集合變爲空並且功能丟失。 爲什麼造成這種行爲?

+1

[ 「本地值」 覆蓋樣式觸發setter方法](https://msdn.microsoft.com/en-us/library/cc265148( v = VS.95)的.aspx)。如果您將背景顏色設置爲XAML中Button元素的屬性,您會得到相同的效果。答案是使用後面的代碼,或添加屬性來公開邏輯並在觸發器中執行,但不要嘗試混合兩者。當你打架時,框架通常會笑到最後。 –

+0

謝謝埃德,對我來說不是很清楚。 – igorGIS

回答

0

依賴屬性比常規C#屬性複雜得多。你在做什麼就是設置一個"Local value", which will override Style trigger setters.如果你將Background筆刷設置在XAML中的Button元素的屬性上,你會得到同樣的效果(但是你可以將它作爲控件的初始狀態,在這裏問爲什麼你的觸發器根本不起作用)。答案是將所有代碼都放在後面,或者添加屬性來顯示邏輯並在觸發器中執行,但不要嘗試混合這兩者。當你打架時,框架通常會笑到最後。我對框架的正面攻擊最好是Pyrrhic victories,而more often debacles

我不建議在代碼背後做這件事,但如果你已經投入了大量時間,那麼你可能會堅持這個項目。但是,這意味着你失去了鼠標懸停的顏色。在代碼背後嘗試這樣做會很麻煩。

值得關注一下我在下面使用的DependencyObject.GetValue()DependencyObject.ReadLocalValue()的MSDN頁面。

我無法用消失的觸發器重現您的行爲。即使在事件處理程序中設置了背景,我仍然有一個觸發器。它只是沒有效果。

XAML:

<Button 
    Click="Button_Click" 
    Content="Click Me" 
    > 
    <Button.Style> 
     <Style TargetType="Button"> 
      <Style.Triggers> 
       <Trigger Property="IsMouseOver" Value="True"> 
        <Setter Property="Background" Value="#3E6DB6" /> 
       </Trigger> 
      </Style.Triggers> 
     </Style> 
    </Button.Style> 
</Button> 

C#:

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    var btn = sender as Button; 
    var triggers = btn.Style.Triggers; 

    // GetValue returns the "effective value": Maybe local, maybe not; 
    // whatever it is, it's the value that will be used. 
    var background = btn.GetValue(Button.BackgroundProperty); 

    // If there's a local value, it overrides whatever else has been set. 
    // Note that a value set by a template trigger on a property of an 
    // element within the template is a local value. 
    var localbackground = btn.ReadLocalValue(Button.BackgroundProperty); 

    // Right now, 
    //  background == #FF3E6DB6 
    //  localbackground == DependencyProperty.UnsetValue 

    btn.Background = new SolidColorBrush(Colors.YellowGreen); 

    background = btn.GetValue(Button.BackgroundProperty); 
    localbackground = btn.ReadLocalValue(Button.BackgroundProperty); 

    // Now they're both #FF9ACD32, which is YellowGreen 
    // triggers.Count == 1 

    btn.Content = $"Trigger count: {triggers?.Count}"; 
}