WPF:DataTrigger只生效了一次

Ymrt
  • 4
新手上路,请多包涵
<Image x:Class="WPFControls.StateIcon"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPFControls" x:Name="_Main"
             mc:Ignorable="d" Style="{DynamicResource ImageStyle1}"
             d:DesignHeight="450" d:DesignWidth="800">
    <Image.Resources>
        <Style TargetType="Image" x:Key="ImageStyle1">
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="0">
                    <Setter Property="Source" Value="{Binding NormalIcon}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="1">
                    <Setter Property="Source"  Value="{Binding WarnIcon}"/>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="2">
                    <Setter Property="Source" Value="{Binding AlarmIcon}"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Image.Resources>
</Image>

DataTrigger只在程序运行初始生效了一次,之后我用其他按钮改变State的值,UI上并没有发生了变化。
XAML如上,我在后台代码上写了DataContext = this;不知道是不是因为这个造成的影响。

回复
阅读 495
1 个回答
Ymrt
  • 4
新手上路,请多包涵
✓ 已被采纳

我修改了写法,使用ControlTemplate去实现,发现依然没有效果,而另一个控件的写法与之是一样的,却能正常显示,最后发现是后台依赖属性写错了......

    <UserControl.Resources>
        <Style  TargetType="{x:Type local:StateIcon}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:StateIcon}">
                        <Image x:Name="_Icon" ></Image>
                        <ControlTemplate.Triggers>
                            <Trigger Property="State" Value="0">
                                <Setter TargetName="_Icon" Property="Source" Value="{Binding NormalIcon}"/>
                            </Trigger>
                            <Trigger Property="State" Value="1">
                                <Setter TargetName="_Icon" Property="Source"  Value="{Binding WarnIcon}"/>
                            </Trigger>
                            <Trigger Property="State" Value="2">
                                <Setter TargetName="_Icon" Property="Source" Value="{Binding AlarmIcon}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </UserControl.Resources>