I want to be able to have a generic style template that can switch colors of my textboxes based on a bool. But I don't want to have to create a unique style for each textbox. How do I do this?
I have put some sample code below how I might expect this to work. Three textboxes, all with different bindings but attempting to use the same template to select red or green colour based on a bool.
Thanks
<TextBlock Text="{Binding Text1}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool1}" />
<TextBlock Text="{Binding Text2}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool2}" />
<TextBlock Text="{Binding Text3}" Style={DynamicResource MyTextBoxTemplate} DataContext="{Binding MyBool3}" />
<Style x:Key="MyTextBoxTemplate" TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Value="True" Binding="{Binding ???}">
<Setter Property="Foreground" Value="Green" />
</DataTrigger>
<DataTrigger Value="False" Binding="{Binding ???}">
开发者_如何学C <Setter Property="Foreground" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
You can use the Tag property of TextBox
<TextBlock Text="{Binding Text1}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool1}" />
<TextBlock Text="{Binding Text2}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool2}" />
<TextBlock Text="{Binding Text3}" Style={DynamicResource MyTextBoxTemplate} Tag="{Binding MyBool3}" />
<Style x:Key="MyTextBoxTemplate" TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="Tag" Value="True">
<Setter Property="Foreground" Value="Green" />
</Trigger>
<Trigger Property="Tag" Value="False">
<Setter Property="Foreground" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
You can also use an attached property for that instead of Tag.
精彩评论