Using DataTrigger with more than one values in WPF

Jainendra picture Jainendra · Apr 18, 2012 · Viewed 12.1k times · Source

I am using XAML code part of which is

<DataTrigger Binding="{Binding Path=Name}" Value="1">
    <Setter Property="Header" TargetName="expanderHeader" Value="Course Text"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Name}" Value="2">
    <Setter Property="Header" TargetName="expanderHeader" Value="Media Lecture"/>
</DataTrigger>
<DataTrigger    Binding="{Binding Path=Name}" Value="3">
    <Setter Property="Header" TargetName="expanderHeader" Value="Assessment"/>

<DataTrigger Binding="{Binding Path=Name}" Value="4">
    <Setter Property="Header" TargetName="expanderHeader" Value="Question"/>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Name}" Value="5">
    <Setter Property="Header" TargetName="expanderHeader" Value="General"/>
</DataTrigger>

Now I want to use a dataTrigger which can have values as 3, 301, 302 or 303. How can I do this. I tried with Multidatatrigger, but it doesn't worked. The code I tried with Multidatatrigger was:

<MultiDataTrigger>
    <MultiDataTrigger.Conditions>
        <Condition Binding="{Binding Path=Name}" Value="301"/>
        <Condition Binding="{Binding Path=Name}" Value="301"/>
        <Condition Binding="{Binding Path=Name}" Value="302"/>
        <Condition Binding="{Binding Path=Name}" Value="303"/>
        </MultiDataTrigger.Conditions>
    <Setter Property="Header" TargetName="expanderHeader" Value="Assessment"/>
</MultiDataTrigger>

Answer

Phil picture Phil · Apr 18, 2012

MultiDataTrigger applies when all of the conditions are met not any, that's why your MultiDataTrigger isn't working.

Either have four separate triggers, or put the condition into a separate boolean property such as

bool ShowAssessment
{
    return Value == 301 || Value == 302 ...
}

raise a property change notification for ShowAssessment when Value changes

e.g

int Value { 
    get{ return _value; } 
    set { 
        _value = value; 
        RaisePropertyChanged("Value");
        RaisePropertyChanged("ShowAssessment");
    }
}

and then trigger on ShowAssessment.

Probably a better solution is to add a HeaderText property with a switch statement that returns the correct header text based on Value. Then just bind the header's text to that. No triggers required.