WPF属性---重复样式和触发器

重复样式

<StackPanel>

<Button FontSize="20" Foreground="Red" Content="hello" Width="100" Height="40"/>

<Button FontSize="20" Foreground="Red" Content="hello" Width="100" Height="40"/>

<Button FontSize="20" Foreground="Red" Content="hello" Width="100" Height="40"/>

</StackPanel>

通过以上的设置我们发现有很多重复的代码,在编写代码的时候,我们要避免代码的重复,代码的冗余,我们需要借助window资源,<window.Resources>

都要设置一个键值,通过键值找到样式X:key,例如:X:key=“defaultStyle”,通过defaultStyle找到样式

设置类型,TargetType。我们要为button设置样式,那么TargetType的类型就是button:TargetType=“button”。在接下来的设置中,我们就可以依据button的属性来设置

<Window.Resources>

<Style x:Key="defaultStyle" TargetType="Button"><!--TargetType要为谁设置样式-->

<Setter Property="FontSize" Value=" 30"/>

<Setter Property="Foreground" Value="blue"/>

<Setter Property="Width" Value="10"/>

</Style>

</Window.Resources>

<Grid>

<StackPanel>

按钮调用

<Button Style="{StaticResource defaultStyle}" Foreground="Red" Content="hello" Width="100" Height="40"/>

<Button FontSize="20" Foreground="Red" Content="hello" Width="100" Height="40"/>

<Button FontSize="20" Foreground="Red" Content="hello" Width="100" Height="40"/>

</StackPanel>

</Grid>

触发器

触发器就像开关一样,比如说一个按钮放上去的时候是什么样的拿下来又是什么样的

<Style.Triggers>

Trigger 为其中的一个触发器,还有其他样式

<Trigger Property="IsMouseOver" Value="True">

设置的各个属性

<Setter Property="Foreground" Value="Red"/>

<Setter Property="FontSize" Value="100"/>

</Trigger>

</Style.Triggers>

表现效果,当鼠标移动到按钮上会发生字体变为共色,字体为100

多条件触发器

<Style.Triggers>

<MultiTrigger><!--多条件触发器 当满足多个条件之后才触发的-->

<MultiTrigger.Conditions>

<!--两个条件同时满足--> 相当于这里是if语句

<Condition Property="IsMouseOver" Value="True"/>

<Condition Property=" IsFocused" Value="True"/>

</MultiTrigger.Conditions>

<!--满足以上两个条件执行什么-->就执行什么语句

<MultiTrigger.Setters>

<Setter Property="Foreground" Value="Red"/>

</MultiTrigger.Setters>

</MultiTrigger>

</Style.Triggers>

事件触发器

<EventTrigger RoutedEvent="Mouse.MouseEnter">

<EventTrigger.Actions>

<BeginStoryboard><!--动画效果-->

<Storyboard>

<DoubleAnimation Duration="0:0:0.2"

Storyboard.TargetProperty="FontSize" To="30">

</DoubleAnimation>

</Storyboard>

</BeginStoryboard>

</EventTrigger.Actions>

</EventTrigger>

Supongo que te gusta

Origin blog.csdn.net/weixin_45309155/article/details/120061756
Recomendado
Clasificación