我想在XAML中使用触发器设置按钮内容,而无需编写代码:
每次点击按钮时,都应更改内容: 像按钮第一次点击,按钮内容=“嗨”,第二次点击,按钮内容=“再见”,第三次点击,按钮内容=“嗨”再次。
<Button x:Name="btn" Content="Hi">
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference btn}"
Storyboard.TargetProperty="Content">
<DiscreteObjectKeyFrame KeyTime="0:0:0"
Value="Bye"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
<StopStoryboard>
</StopStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
所以它适用于将按钮内容设置为Bye,但是如何在下一次单击时将其设置回Hi?
我也不确定这是否是设置触发器的最有效方法,如果你有更好的解决方案,请随意。
答案 0 :(得分:4)
你想要一个具有两个状态的按钮,它看起来就像是一个ToggleButton。 这是一种改变内容的样式:
<Style x:Key="ToggleButtonStyle1" TargetType="{x:Type ToggleButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsDefaulted" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="Red"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="border" Value="#FFBEE6FD"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FF3C7FB1"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" TargetName="border" Value="#FFC4E5F6"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FF2C628B"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" TargetName="contentPresenter" Value="Bye"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" TargetName="border" Value="#FFF4F4F4"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FFADB2B5"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="#FF838383"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>