views:

166

answers:

3

I have a DataTrigger defined in my XAML which I want to use in several places. Is it possible to define it as a resource and then share it?

Here's my trigger:

<TextBlock.Style>
    <Style>
        <Style.Triggers>
            <DataTrigger Binding="{Binding HasCurrentTest}" Value="True">
                <Setter Property="TextBlock.Visibility" Value="Hidden" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

While I can define this in my Window.Resources and give it a key, how do I refer to it in the rest of my XAML?

A: 

If the style is in the Windows.Resources with a key, each element can add it to their own style like this.

<Window.Resources>
    <Style x:Key="YourStyleKey">
        <!-- Your Style -->
    </Style>
</Window.Resources>

<TextBox Text="SomeText" Style="{StaticResource YourStyleKey}"/>
<TextBox Text="SomeOtherText" Style="{StaticResource YourStyleKey}"/>
MrSlippers
I don't think this is a preferable answer because Styling should be left for real styling, not Data driven logic. You'd run into a problem here if you decided later to style your entire application; you'd have to provide special cases of styles that merge the Style and the logic behavior.
Daniel Jennings
Yes, I agree - this is what I'm wanting to avoid - I want to share the DataTrigger, not the Style itself.
Craig Shearer
+2  A: 

As a comment on my own post, I've just seen a much better way to do this anyway - I should be using the built-in BooleanToVisibilityConverter, then I can just do this:

<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis" />
</Window.Resources>

then...

<TextBlock Visibility="{Binding HasNoCurrentTest, 
           Converter={StaticResource BoolToVis}}" />

which is a much better solution!

Craig Shearer
A: 

Of course I now need a BooleanToHiddenConverter - maybe I'll have to write this myself :-)

Craig Shearer