DataTrigger没有发射DataTrigger

2023-09-03 23:22:43 作者:故事与她

我有以下的XAML:

    <DockPanel>
    <DockPanel>
        <CheckBox IsChecked="{Binding Path=Test}" />
        <CheckBox IsChecked="{Binding Path=Test}" />
    </DockPanel>
    <DockPanel DockPanel.Dock="Left" Width="10" Background="Blue">
        <DockPanel.Style>
            <Style>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Path=Test}" Value="True">
                        <Setter Property="DockPanel.Background" Value="Yellow" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DockPanel.Style>
    </DockPanel>
</DockPanel>

现在 - 2复选框链接正确 - 检查一会检查对方 - 但datatrigger在不触发所有

Now - the 2 checkboxes link properly - checking one will check the other - but the datatrigger is not firing at all.

我是什么做错了吗?

推荐答案

这里的问题是属性值precedence 。

您是在目前的背景设置为蓝色直接在DockPanel中。这种明确的属性将覆盖由触发器设置的任何值。

You are currently setting the Background to blue directly on the DockPanel. This explicit property will override any value set by the trigger.

相反,你必须将原来的背景作为风格引领者。

Instead, you must set the original "Background" as a setter in the style.

   <DockPanel DockPanel.Dock="Left" Width="10">
       <DockPanel.Style>
           <Style>  
                <Setter 
                        Property="DockPanel.Background"
                             Value="Blue" /> 
               <Style.Triggers>                    
                   <DataTrigger 
                           Binding="{Binding Path=Test}"
                           Value="True">                        
                   <Setter 
                        Property="DockPanel.Background"
                             Value="Yellow" />                       
                    </DataTrigger>                </Style.Triggers>            </Style>        </DockPanel.Style>    </DockPanel></DockPanel>