havardhu
havardhu

Reputation: 3616

WPF hierarchical triggers

Is it possible to write a custom trigger in WPF that could be evaluated hierarchically?

Update: In this example I have used themes, but based on the initial comments it seems like I have to clarify that I am not asking for ways to implement theme support in WPF - it is writing custom triggers and the abstract concept of a hierarchical trigger that is of interest here, as an alternative to MultiTrigger

In code you would write

if (theme == Themes.Black){
    if (IsMouseOver)
       Background = Brushes.Cyan;
    if (IsSelected)
       Background = Brushes.Red;
}
if (theme == Themes.White){
    if (IsMouseOver)
       Background = Brushes.Black;
    if (IsSelected)
       Background = Brushes.Grey;
}

However when expressing this kind of logic with triggers you have to create a set of MultiTriggers

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Theme" Value="Black">
        <Condition Property="IsMouseOver" Value="True">
    </MultiTrigger.Conditions>
    <Setter Property="Background" Value="Cyan" />
</MultiTrigger>
<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Theme" Value="White">
        <Condition Property="IsMouseOver" Value="True">
    </MultiTrigger.Conditions>
    <Setter Property="Background" Value="Black" />
</MultiTrigger>
// And so on...

This quickly turns unmanageable for complex controls, so I tried to picture a way to prettify this, and came up with an idea for the following syntax:

<HierarchicalTrigger Property="Theme" Value="Black">
    <HierarchicalTrigger.Triggers>
         <Trigger Property="IsMouseOver" Value="True">
           <Setter Property="Background" Value="Cyan" />
         </Trigger>
         <Trigger Property="IsSelected" Value="True">
           <Setter Property="Background" Value="Red" />
         </Trigger>
    </HierarchicalTrigger.Triggers>
</HierarchicalTrigger> 

<HierarchicalTrigger Property="Theme" Value="White">
    <HierarchicalTrigger.Triggers>
         <Trigger Property="IsMouseOver" Value="True">
           <Setter Property="Background" Value="Black" />
         </Trigger>
         <Trigger Property="IsSelected" Value="True">
           <Setter Property="Background" Value="Grey" />
         </Trigger>
    </HierarchicalTrigger.Triggers>
</HierarchicalTrigger> 

Does anyone know if such a trigger can be written, and/or have any tips on how to go about doing this?

Upvotes: 1

Views: 199

Answers (1)

Markus H&#252;tter
Markus H&#252;tter

Reputation: 7906

I'll go ahead and provide an answer:

No it's not possible.

Anything that goes in <Triggers> needs to inherit from TriggerBase. Taking a look at it you'll see that the most important virtual methods (GetCurrentState() and Seal()) are internal so you'll not be able to modify that behavior unless you're Microsoft.

Upvotes: 1

Related Questions