简体   繁体   English

无法在WPF中设置DataTrigger

[英]Trouble setting a DataTrigger in WPF

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). 我在主视图上有一个ComboBox和一个Button ,我想在按钮上应用一个样式,这样当组合框索引设置为1时,按钮变为可见(最初它是隐藏的)。 This is my XAML code: 这是我的XAML代码:

<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. 有人在这里问了一个关于这个的问题,而且我做了几乎相同的事情,但它不起作用,即使索引更改为1,按钮仍然隐藏。最初在后面的代码中填充了comobox有2件物品。 Any help is appreciated. 任何帮助表示赞赏。

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 : 简单的解决方案是在样式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. 当你在这里时,你应该看看这个列出设置DP值的优先顺序的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM