我有一个按钮控件,其Content属性绑定到我的viewmodel上的boolean属性。该按钮用于打开和关闭工业机器上的阀门,通过异步WCF调用执行。当服务返回时,它会更新boolean属性,进而触发对按钮的可视状态的更改。这是按钮xaml:
<Button Command="{Binding Path=OpenCloseValveCommand}"
Content="{Binding Path=ValveIsOpen}"
Style="{StaticResource ResourceKey=OnOffButtonStyle}">
当阀门打开时,按钮需要为绿色,当阀门关闭时,按钮需要穿过红色。这是样式xaml:
<Style TargetType="Button" x:Key="OnOffButtonStyle" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Canvas>
<Rectangle x:Name="_rect" Fill="Red" Stroke="Black" Width="30" Height="30"></Rectangle>
<Path x:Name="_path" Data="M0,0 L30,30 M0,30 L30,0" StrokeThickness="1" Stroke="Black" />
</Canvas>
<ControlTemplate.Triggers>
<Trigger Property="Content" Value="true">
<Setter TargetName="_rect" Property="Fill" Value="Lime" />
<Setter TargetName="_path" Property="Visibility" Value="Hidden" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
不幸的是触发器似乎没有触发。我猜这与按钮内容绑定到布尔类型有关 - 我是否需要使用“true”之外的其他内容作为触发值? (如果我将viewmodel属性更改为整数并使用0或1,并且触发值为“1”,则触发器有效。
提前致谢
安迪
答案 0 :(得分:11)
您可以明确指定类型:
<Window ...
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...>
<Trigger Property="Content">
<Trigger.Value>
<sys:Boolean>True</sys:Boolean>
</Trigger.Value>
<Setter TargetName="_rect" Property="Fill" Value="Lime" />
<Setter TargetName="_path" Property="Visibility" Value="Hidden" />
</Trigger>
答案 1 :(得分:0)
使用DataTrigger
:
<Button Command="{Binding Path=OpenCloseValveCommand}"
Style="{StaticResource ResourceKey=OnOffButtonStyle}">
<Style TargetType="Button" x:Key="OnOffButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Canvas>
<Rectangle x:Name="_rect" Fill="Red" Stroke="Black" Width="30" Height="30"></Rectangle>
<Path x:Name="_path" Data="M0,0 L30,30 M0,30 L30,0" StrokeThickness="1" Stroke="Black" />
</Canvas>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding ValveIsOpen}" Value="True">
<Setter TargetName="_rect" Property="Fill" Value="Lime" />
<Setter TargetName="_path" Property="Visibility" Value="Hidden" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>