4

I'm trying to setup a trigger so if two values match a color change happens, this is easy when the thing to match is static and can be placed right into xaml, but not when the thing to be compared is dynamic, such as a property. Basically is there anyway to bind the value of a trigger to a property?

Example - Error says value can not use a binding. This leads me to think that value has to be static.

<TextBlock Name="MyTextBlock" Text="{Binding someProp}">
    <TextBlock.Resources>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=MyTextBlock, Path=Text}" Value="{Binding someOtherProperty}">
                    Do some stuff here
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Resources>
</Textblock>

EDIT: Updated it to a data trigger, but the issue remains.

Jacob McCarthy
  • 218
  • 3
  • 15
  • 1
    possible duplicate of [Using binding for the Value property of DataTrigger condition](http://stackoverflow.com/questions/2240421/using-binding-for-the-value-property-of-datatrigger-condition) or [Using bindings in DataTrigger condition](http://stackoverflow.com/q/2239839/620360). – LPL Jun 04 '15 at 19:36
  • Note that the OP in a comment on the answer has effectively agreed that this is a duplicate of https://stackoverflow.com/questions/2240421/using-binding-for-the-value-property-of-datatrigger-condition. – StayOnTarget May 13 '22 at 19:46

1 Answers1

4

For this purpose you may use DataTriggers like shown in the example below (TextBlock named txtBlock color changes depends on the value "R" or "N"):

<Style.Triggers>
    <DataTrigger Binding="{Binding ElementName=txtBlock,Path=Text}" Value="R">
            <Setter Property="Background" Value="#f9f9f9" />
            <Setter Property="Foreground" Value="Red" />
    </DataTrigger>
    <DataTrigger Binding="{Binding ElementName=txtBlock,Path=Text}" Value="N">
        <Setter Property="Background" Value="Yellow" />
        <Setter Property="Foreground" Value="Black" />
    </DataTrigger>
</Style.Triggers>

Solution works for any finite data set used in condition. For more complex condition (e.g. variable used in condition block, etc) you can implement the value converter and binding in code-behind like shown in the example: Binding in WPF DataTrigger value. Also, you may consider MultiDataTrigger, or DataTrigger with MultiBinding (re: MultiDataTrigger vs DataTrigger with multibinding).

Hope this may help.

Community
  • 1
  • 1
Alexander Bell
  • 7,842
  • 3
  • 26
  • 42