Trouble setting a DataTrigger in WPF

ε祈祈猫儿з 提交于 2020-02-03 05:13:13

问题


I have a ComboBox and a Button on my main view, and I want to apply a style to the button such that when the combobox index is set to 1, the button becomes visible (initially it's hidden). This is my XAML code:

<Grid>
    <StackPanel Orientation="Vertical" Margin="10">
        <ComboBox Name="comboBox"/>

        <Button Name="myBtn" Content="Hello" Visibility="Hidden">
             <Button.Style>
                 <Style TargetType="{x:Type Button}">
                     <Style.Triggers>
                         <DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedIndex}" Value="1">
                             <Setter Property="Visibility" Value="Visible"/>
                          </DataTrigger>
                      </Style.Triggers>
                  </Style>
              </Button.Style>
         </Button>
     </StackPanel>
</Grid>

Someone already asked a question about this here, and I'm doing pretty much the same thing, but it doesn't work, the button remains hidden even when the index is changed to 1. The comobox is initially being populated in the code behind with 2 items. Any help is appreciated.


回答1:


The problem is that dependency property values set locally (like you've done with visibility) have a higher precedence then those set from a style trigger. As such, even when the trigger is hit, it won't override the value you've already set.

The simple solution is to instead set the default value in a style Setter:

    <Button Name="myBtn" Content="Hello">
         <Button.Style>
             <Style TargetType="{x:Type Button}">
                 <Setter Property="Visibility" Value="Hidden"/>
                 <Style.Triggers>
                     <DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedIndex}" Value="1">
                         <Setter Property="Visibility" Value="Visible"/>
                      </DataTrigger>
                  </Style.Triggers>
              </Style>
          </Button.Style>
     </Button>

And now your trigger will override the property value when it is hit.

While you're at it, you should have a look at this link that lists the precedence order for setting DP values.



来源:https://stackoverflow.com/questions/16448098/trouble-setting-a-datatrigger-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!