WPF style and Resource
In controls, we can set their styles through properties. If we want to use the same style for many controls. What should I do?
Method 1: This is the attribute of each control. Obviously, this is not a wise choice.
Then we will use 2:
We can set it in style. Resource in its parent container. In this way, other controls (in the same parent container) can also be accessed.
The following is a demo.
We now drag three button controls on the form. We set its style in window. Resources.
<Window. Resources> <style X: Key ="Btnstyle"Targettype ="Button"> <Setter property ="Background"Value ="Yellow"/> </Style> </window. Resources>
Targettype is used to identify the bound object.
Next we will bind the style on the button.
<Grid> <button style =" {Staticresource btnstyle} "Content =" Button "Height =" 43 "Horizontalalignment =" Left "Margin =" "Name =" Button1 "Verticalalignment =" Top "Width =" 88 "/> <Button style =" {Staticresource btnstyle} "Content =" Button "Height =" 43 "Horizontalalignment =" Left "Margin =" 149,35, 0, 0 "Name =" Button2 "Verticalalignment =" Top "Width =" 85 "/> <Button style =" {Staticresource btnstyle} "Content =" Button "Height =" 43 "Horizontalalignment =" Left "Margin =" 261,35 "Name ="Button3 "Verticalalignment =" Top "Width =" 84 "/> </GRID>
Actually, this style = "{staticresource btnstyle }"
:
What I just changed is the background color. What about the foreground color?
We only need to add
<Setter property = "foreground" value = "red"/>
If we want to give him some events. For example, what changes will happen when you move the mouse over the button, and what changes will happen when you press it.
This requires style. triggers.
<Window. Resources> <style X: Key =" Btnstyle "Targettype =" Button "> <Style. triggers> <trigger property =" Button. ismouseover "Value =" True "> <Setter property =" Background "Value =" Lightblue "/> </Trigger> <trigger property =" Button. ispressed "Value =" True "> <Setter property =" Background "Value =" Blue "/> </Trigger> </style. triggers> <setter property ="Background "Value =" Yellow "/> <Setter property =" Foreground "Value =" Red "/> </Style> </window. Resources>
See the inserted style. triggers.
:
Move the mouse over.
Press the mouse
The difference is not clear because the two colors are similar.
End.