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