WPF Trigger when Property and Data value are true
Asked Answered
L

2

11

I need to be able to change the Style of a control when a property and data value are true. For example, my bound data has an IsDirty property. I would like to change the background color of my control when IsDirty is true AND the control is selected. I found the MultiTrigger and MultiDataTrigger classes...but in this case I need to somehow trigger on data and property. How can I do this?

Another note: I need to be able to do this in code behind not XAML.

Laine answered 27/5, 2010 at 14:8 Comment(0)
O
20

MultiDataTrigger works just as well for DependencyProperties as it does for ordinary properties. Just set the Path in the binding to the name of your dependency property.

You will need to be careful about setting the source of that binding though, since by default the source is the DataContext of the element to which the trigger is attached. If the trigger is used in a style on the selectable object, your can use the RelativeSource property of the Binding:

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
      <Condition Binding="{Binding Path=IsDirty}" Value="True" />
      <Condition Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Self}}" Value="True" />
    </MultiDataTrigger.Conditions>
    <Setter Property="Background" Value="Cyan" />
  </MultiDataTrigger>
Olivaolivaceous answered 27/5, 2010 at 14:12 Comment(3)
Could you give an example please? Sorry I'm pretty new to WPF.Laine
I actually need to do this in code-behind for my particular case. The only part I cant figure out is how to specify RelativeSource Self. Do you know how to do this?Laine
Figured it out, marking your answer as correct and then I'll post the code-behind version I used for anyone else in the same situation.Laine
L
0

Here's how I actually did it in code-behind:

new MultiDataTrigger
{
    Conditions = 
    {
        new Condition
        {
            Binding = new Binding("IsDirty"),
            Value = true
        },
        new Condition
        {                                                    
            Binding = new Binding("IsSelected") { RelativeSource = RelativeSource.Self },
            Value = true
        }
    },

    Setters =
    {
        new Setter
        {
            Property = Control.BackgroundProperty,
            Value = Brushes.Pink
        }
    }
}
Laine answered 27/5, 2010 at 14:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.