Chris
Chris

Reputation: 27384

XAML - Generic textbox stylewith triggers / parameters?

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 ???}">
                        <Setter Property="Foreground" Value="Red" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

Upvotes: 1

Views: 1433

Answers (2)

Matthias
Matthias

Reputation: 12259

You can also use an attached property for that instead of Tag.

Upvotes: 1

Arcturus
Arcturus

Reputation: 27055

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>

Upvotes: 1

Related Questions