Search code examples
c#wpfxamlbindingwpf-style

How to reuse style with two different bindings?


I have this Style:

<Style x:Key="BlinkStyle">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=BlinkForError, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type loc:DevicesRepositoryEditorUserControl}}}"
                     Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard Name="BlinkBeginStoryboard">
                    <Storyboard>
                        <ColorAnimation To="Red" Storyboard.TargetProperty="(Background).(SolidColorBrush.Color)"
                                                        FillBehavior="Stop" Duration="0:0:0.4" RepeatBehavior="Forever" AutoReverse="True" />
                    </Storyboard>
                </BeginStoryboard>
            </DataTrigger.EnterActions>
            <DataTrigger.ExitActions>
                <StopStoryboard BeginStoryboardName="BlinkBeginStoryboard" />
            </DataTrigger.ExitActions>
        </DataTrigger>
    </Style.Triggers>
</Style>

Whenever the bound dependency-property BlinkForError is set to True, it start blinking. It works great, like this:

<!-- When BlinkForError set to True, this TextBox, named "One", blinks: -->
<TextBox Name="One" Style="{StaticResource ResourceKey=BlinkStyle}"/>

Thing is that I want exactly the same thing, but bound to another dependency-property, say AnotherBlinkForError:

<!-- When AnotherBlinkForError set to True, this TextBox, named "Two", blinks: -->
<TextBox Name="Two" Style="{StaticResource ResourceKey=AnotherBlinkStyle}"/>

I can duplicate the whole style and only change the DataTrigger's Binding part.

Is there a way to avoid this duplication, reuse the same Style twice with two different bindings?


Solution

  • You could try and make use of the Tag properties on your TextBoxes and bind them to the BlinkForError and BlinkForAnotherError. In your style definition the binding will check the Tag value (you'd probably have to use RelativeSource and FindAncestor options) instead of the Blink properties.

    But to be honest, if there are only two TextBoxes and respective error properties I would go with two separate styles as it's just less hassle.