Today, we made a classic example when learning the WPF dependency attribute, that is, using the Trigger in XMAL to change the foreground color of the button. The Code is as follows:
Code
<Button>
OK
<Button. Style>
<Style targettype = "{X: type button}">
<Style. triggers>
<Trigger property = "ismouseover" value = "true">
<Setter property = "foreground" value = "blue"> </setter>
</Trigger>
</Style. triggers>
</Style>
</Button. Style>
</Button>
You can easily move the mouse over the button, and then the foreground color of the button turns blue.
However, I tried to set a Foreground attribute for this button. Code:
Code
<Button foreground = "black">
OK
<Button. Style>
<Style TargetType = "{x: Type Button}">
<Style. Triggers>
<Trigger Property = "IsMouseOver" Value = "True">
<Setter Property = "Foreground" Value = "Blue"> </Setter>
</Trigger>
</Style. triggers>
</Style>
</Button. Style>
</Button
In this case, the effect of setting the color of the Trigger is invalid. So this reminds me of an article about the Dependency attribute computing sequence I have seen over the past few days.
Http://www.cnblogs.com/YilingLai/archive/2006/12/25/602889.html)
When we calculated the basic value in the first step, the system calculated the value of the Dependency Attribute Based on the following priority:
1. Local Value
2. Style Triggers
3. Template Triggers
4. Style Setters
5. Theme Style Triggers
6. Theme Style Setters
7. Property Value Inheritance
8. Default Value
Because Foreground = "Black" belongs to the Local Value and has a higher priority than Style Triggers
It masks the effect of Style Triggers on the Foreground attribute value.
So you need to set Foreground and set Trigger to change it. How can this problem be solved?
The answer is as shown in the following code:
Code
<Window. Resources>
<Style targettype = "{X: type button}" X: Key = "changecolorstyle">
<Style. triggers>
<Trigger Property = "IsMouseOver" Value = "True">
<Setter Property = "Foreground" Value = "Blue"> </Setter>
</Trigger>
</Style. Triggers>
<Setter Property = "Foreground" Value = "Black"> </Setter>
</Style>
</Window. Resources>
<StackPanel>
<Button Style = "{StaticResource changeColorStyle}">
OK
</Button>
</StackPanel
Extract the Style to Window. Resources, and then make this Button reference this resource.
When calculating the order of basic values, Style Triggers ranks second, while Style Setter ranks fourth.
Code