I have several StackPanels that change visibility based on ToggleButtons. The code below works if I replace Tag with btn1 on the DataTrigger-lines.
How do I use the value of the Tag property?
<Window x:Class="MyTestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestApp">
<Window.Resources>
<Style x:Key="panelStyle" TargetType="{x:Type StackPanel}">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=Tag, Path=IsChecked}" Value="False">
<Setter Property="StackPanel.Visibility" Value="Collapsed" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=Tag, Path=IsChecked}" Value="True">
<Setter Property="StackPanel.Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<WrapPanel>
<ToggleButton Content="One" Name="btn1" />
<ToggleButton Content="Two" Name="btn2" />
<StackPanel Style="{StaticResource panelStyle}" Tag="{Binding btn1}">
<Label Content="Data to panel 1" />
</StackPanel>
<StackPanel Style="{StaticResource panelStyle}" Tag="{Binding btn2}">
<Label Content="Data to panel 2" />
</StackPanel>
</WrapPanel>
</Window>
This question is very similar, but I’m missing details on how to pass an element name.
XAML – Generic textbox stylewith triggers / parameters?
Your bindings are incorrect.
In your
DataTemplatethe bindings should be:Here the
RelativeSourcewith a mode ofSelftells the binding engine that the object to bind against is object to which the style is being applied (e.g. yourStackPanel). ThePropertyPathofTag.IsCheckedtells the binding engine to look for a property calledIsCheckedfrom the object stored inTag.Finally the bindings in your
StackPanelshould be:Here
ElementNamecreates a binding to another element in the logical tree. If you do not explicitly assign to any properties in aBindingas in your original example:The value specified is assigned to the
Pathproperty. So this would be the same as:Also note, that using
Tagis not considered best practice since it’s type is ofobjectand its use is unrestricted, and hence can take on any number of different meanings throughout your project (which often makes it difficult to understand, especially when used inTemplatesthat are located far away from their actual use).Hope this helps!