Search code examples
wpfdatatrigger

Is it possible to modify a textbox style to use a particular datatrigger?


I have a TextBox that uses a style that is common to all the TextBoxes, so I can have the same aspect for all of them.

However, in a particular TextBox, I need to modify its visibily according to a condition, so I am trying to do this:

<TextBox 
    Text="{Binding MyBinding, Mode=OneWay}"
    Style="{StaticResource TextBoxStyle1}">
    <TextBox.Style>
        <Style TargetType="StackPanel">
            <Setter Property="Visibility" Value="Visible"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=thisView, Path=DataContext.MyPropertyInViewModel}" Value="3">
                    <Setter Property="Visibility" Value="Collapsed"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

The problem is that i can't set the style twice, so I don't know how to define the data trigger to hide the textBox.

How could I do that?

Thanks.


Solution

  • Remove the Style="{StaticResource TextBoxStyle1}" and add the BasedOn tag to the new style BasedOn="{StaticResource TextBoxStyle1}"

    <TextBox 
        Text="{Binding MyBinding, Mode=OneWay}">
        <TextBox.Style>
            <Style TargetType="StackPanel" BasedOn="{StaticResource TextBoxStyle1}">
                <Setter Property="Visibility" Value="Visible"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=thisView, Path=DataContext.MyPropertyInViewModel}" Value="3">
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </TextBox.Style>
    </TextBox>
    

    That will allow you to reuse the existing style. However, if the existing style already defines a DataTrigger that you don't want, you will need to create a new style for this textbox.