Suppose I want to show/hide elements based on Values of Properties from DataContext, how can I acheive it?
// In MainWindow.xaml.cs: DataContext of MainWindow.xaml
public int Mode { get; set; }
In XAML, I want to show hide elements based on the Mode. How can I make the below work? Or what is the appropriate way of implementing this?
<StackPanel>
<StackPanel.Triggers>
<Trigger Property="Mode" Value="1">
<Setter TargetName="txt1" Property="Visibility" Value="Visible" />
<Setter TargetName="txt2" Property="Visibility" Value="Collapsed" />
<Setter TargetName="txt3" Property="Visibility" Value="Visible" />
</Trigger>
<Trigger Property="Mode" Value="2">
<Setter TargetName="txt1" Property="Visibility" Value="Collapsed" />
<Setter TargetName="txt2" Property="Visibility" Value="Visible" />
<Setter TargetName="txt3" Property="Visibility" Value="Collapsed" />
</Trigger>
</StackPanel.Triggers>
<TextBlock Text="TextBlock 1" x:Name="txt1" />
<TextBlock Text="TextBlock 2" x:Name="txt2" />
<TextBlock Text="TextBlock 3" x:Name="txt3" />
</StackPanel>
Currently, the Error I am getting is “Property ‘Mode’ was not found in type ‘StackPanel’. D:\tmp\WpfApplication1\TriggersAndProperties\MainWindow.xaml“
You need to use
DataTriggersif you want triggers that can work on bindings. Problem is,DataTriggersare only available on style and template so you need to define one like this:Another solution would be to use an
IValueConverterthat converts the int fromModeto theVisibilityyou want, and apply it directly to each text blockVisibilityproperty.Note that Dean Chalk’s answer stays valid: you have to use a
DependencyPropertyor implementINotifyPropertyChangedif you want changes onModeto trigger.