Binding Variables in Style Resources
Posted: 23 Jan 2023, 18:53
Hi,
so I found this amazing code snippet which hides the Border by default and only if my SelectedArticle variable is ARTICLE_A it becomes visible.
The problem is that I have to repeat it in every single Border I want to use this functionality. I would love to put this into my Resources and set the Value (ARTICLE_A, ARTICLE_B, ...) from the Border instead.
This would make my XAML significantly more readable.
How it is:
How I would like it to be:
so I found this amazing code snippet which hides the Border by default and only if my SelectedArticle variable is ARTICLE_A it becomes visible.
The problem is that I have to repeat it in every single Border I want to use this functionality. I would love to put this into my Resources and set the Value (ARTICLE_A, ARTICLE_B, ...) from the Border instead.
This would make my XAML significantly more readable.
How it is:
Code: Select all
<Border>
<Border.Style>
<Style TargetType="Border">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedArticle}" Value="ARTICLE_A">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="Text of Article A"/>
</Border>
Code: Select all
private enum Articles {
ARTICLE_A,
ARTICLE_B,
ARTICLE_C
}
private Article selectedArticle;
public string SelectedArticle { get => selectedArticle; }
Code: Select all
<UserControl.Resources>
<Style x:Key="InvisibleBorderTemplate" TargetType="Border">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedArticle}" Value="VALUE_OF_STYLE_RESOURCE">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<Border Style="{StaticResource InvisibleBorderTemplate}" ValueOfStyleResource="ARTICLE_A">
<TextBlock Text="Text of Article A"/>
</Border>
<Border Style="{StaticResource InvisibleBorderTemplate}" ValueOfStyleResource="ARTICLE_B">
<TextBlock Text="Text of Article B"/>
</Border>
<Border Style="{StaticResource InvisibleBorderTemplate}" ValueOfStyleResource="ARTICLE_C">
<TextBlock Text="Text of Article C"/>
</Border>
</Grid>