Troubleshoot DataTrigger in WPF

I have a ComboBox and Button in my main view, and I want to apply a style to the button so that when the combobox index is set to 1, the button becomes visible (it is initially 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 do almost the same thing, but it does not work, the button remains hidden even when the index changes to 1. First, the combobox is filled in the code with two elements. Any help is appreciated.

+6
source share
1 answer

The problem is that dependency property values โ€‹โ€‹set locally (for example, you did with visibility) have a higher priority than those set from a style trigger. Thus, even when the trigger fires, it does not cancel the value that you have already set.

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

  <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 value of the property when it hits.

While you are on it, you should take a look at this link , which indicates the priority order for setting DP values.

+15
source

Source: https://habr.com/ru/post/944559/


All Articles