WPF:DataTrigger只生效了一次

<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;不知道是不是因为这个造成的影响。

阅读 2.3k
1 个回答
✓ 已被采纳新手上路,请多包涵

我修改了写法,使用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>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏