2

我有一个按钮控件,它的 Content 属性绑定到我的视图模型上的布尔属性。该按钮用于打开和关闭工业机器上的阀门,通过异步 WCF 调用执行。当服务返回时,它会更新布尔属性,进而触发按钮视觉状态的更改。这是按钮 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”,则触发器会起作用)。

提前致谢

安迪

4

2 回答 2

13

您可以明确指定类型:

<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>
于 2012-04-17T11:50:48.563 回答
0

使用 a 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>
于 2012-04-17T11:46:06.357 回答