Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 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.

like image 441
PoweredByOrange Avatar asked May 08 '13 18:05

PoweredByOrange


1 Answers

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.

like image 124
dlev Avatar answered Sep 23 '22 00:09

dlev