触发器不更新

时间:2012-06-29 14:17:06

标签: wpf mvvm triggers visualstatemanager multidatatrigger

以下是我想要做的伪代码

IF NOT ISDIRTY
    THEN VISIBILITY EQ VISIBILITY.COLLAPSED

IF ISDIRTY AND ISVALID        
    THEN VISIBILITY EQ VISIBILITY.VISIBLE AND COLOR = GREEN

IF ISDIRTY AND NOT ISVALID        
    THEN VISIBILITY EQ VISIBILITY.VISIBLE AND COLOR = RED

下面的ToggleButton样式在第一次更新时获得正确的条件,但此后不会更改。

例如,如果我进行的更改不会使vm无效,则颜色正确为绿色。但是,如果我然后进行更改以使vm无效,它将保持绿色,当它应该是红色时。相反,如果第一次更新使vm无效,则颜色正确设置为红色,但是第二次更新可以纠正无效错误但使vm变脏并不会将颜色更改为绿色。

我做错了什么?

我还没有尝试过Visual State Manager,但这会是一种首选方式吗?那看起来怎么样?

用法

        <Ellipse Style="{StaticResource EditedStateIndicatorStyle}"/>

样式

<Style x:Key="EditedStateIndicatorStyle" TargetType="{x:Type Ellipse}">
    <Setter Property="Width" Value="8" />
    <Setter Property="Height" Value="8" />
    <Setter Property="Margin" Value="8,0"/>
    <Setter Property="SnapsToDevicePixels" Value="false" />
    <Setter Property="Focusable" Value="False" />

    <Style.Triggers>

        <!-- Dirty, && NOT Valid -->
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding IsDirty}" Value="true"/>
                <Condition Binding="{Binding IsValid}" Value="false"/>
            </MultiDataTrigger.Conditions>
            <Setter Property="Fill" Value="Red"/>
            <Setter Property="ToolTip" Value="You got errors, fool!"/>
        </MultiDataTrigger>

        <!-- Dirty, but Valid -->
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding IsDirty}" Value="true"/>
                <Condition Binding="{Binding IsValid}" Value="true"/>
            </MultiDataTrigger.Conditions>
            <Setter Property="Fill" Value="Green"/>
            <Setter Property="ToolTip" Value="You made changes!"/>
        </MultiDataTrigger>

        <!-- Not Dirty, don't show anything -->
        <DataTrigger Binding="{Binding IsDirty}" Value="false">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
    </Style.Triggers>

</Style>

2 个答案:

答案 0 :(得分:2)

如果您的ViewModel正在实施INotifyPropertyChanged,请首先确保它正确地引发了该事件。说我建议简化:

<Style TargetType="{x:Type Ellipse}">
    ...
    <Setter Property="Fill" Value="Green" />
    <Setter Property="ToolTip" Value="You made changes!" />

    <Style.Triggers>
        <!-- Dirty, but NOT Valid -->
        <DataTrigger Binding="{Binding IsValid}" Value="false">
            <Setter Property="Fill" Value="Red" />
            <Setter Property="ToolTip" Value="You got errors, fool!" />
        </DataTrigger>

        <!-- Not Dirty, don't show anything -->
        <DataTrigger Binding="{Binding IsDirty}" Value="false">
            <Setter Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
    </Style.Triggers>
</Style>

答案 1 :(得分:1)

尝试将填充设置为默认颜色(绿色)作为触发器外部的设置器(即样式中)