Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using triggers as resources

I want to define triggers as resources to use them later in my controls.

Like this:

<Window.Resources>
    <DataTrigger x:Key="Trigger1" Binding="{Binding ViewModelProperty1}" Value="Val1">
        <Setter Property="IsEnabled" Value="False"/>
    </DataTrigger>
    <DataTrigger x:Key="Trigger2" Binding="{Binding ViewModelProperty2}" Value="Val2">
        <Setter Property="IsEnabled" Value="False"/>
    </DataTrigger>
    ...
</Window.Resources>

However, when I try to run the code, the compiler complains that IsEnabled is not a valid member. I think this is because it cannot know if the control in question will even have the property "IsEnabled". Like with styles, I think I need to somehow specifiy the TargetType (which would be, in my case, FrameworkElement). But how?

NOTE:

Please do not suggest to use styles instead of triggers as resources. Since a control can only have ONE style, but I need to give SEVERAL triggers to one control, styles are no option here:

In my actual code I have a Button that should have trigger 1, 2 and 4 and a TextBox that should have trigger 1 and 3 and a Label that should have trigger 2, 3 and 4... I think you get it.

like image 385
Kjara Avatar asked Oct 07 '16 11:10

Kjara


1 Answers

You can do it like this (note how I prepend IsEnabled with FrameworkElement and also how I reference those resources from style triggers):

<Window.Resources>
    <DataTrigger x:Key="Trigger1"
                 Binding="{Binding ViewModelProperty1}"
                 Value="Val1">
        <Setter Property="FrameworkElement.IsEnabled"
                Value="False" />
    </DataTrigger>
    <DataTrigger x:Key="Trigger2"
                 Binding="{Binding ViewModelProperty2}"
                 Value="Val2">
        <Setter Property="FrameworkElement.IsEnabled"
                Value="False" />
    </DataTrigger>
</Window.Resources>
<Button>
    <Button.Style>
        <Style>
            <Style.Triggers>
                <StaticResource ResourceKey="Trigger1" />
                <StaticResource ResourceKey="Trigger2" />
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>
like image 165
Evk Avatar answered Nov 07 '22 07:11

Evk