Search code examples
wpf.net-7.0

How to emulate TargetNullValue in binding?


I want a style to be bound to a nullable colour. If there is value - it uses that value to create solid colour brush otherwise use another colour. I cant use binding TargetNullValue because the another colour is a binding. For example:

<Setter Property="Foreground">
    <Setter.Value>
        <PriorityBinding TargetNullValue="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}">
            <Binding Path="Row.ForegroundColour" IsAsync="True" Converter="{StaticResource colourConverter}"/>
            <Binding Path="Foreground" ElementName="me" IsAsync="True"/>
        </PriorityBinding>

generates error:

A 'Binding' cannot be set on the 'TargetNullValue' property of type 'PriorityBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.'

Whats the realistic way to achieve a simple logical functionality - use colour if it is set and use a default colour if it doesnt (considering both colours are coming from binding)?


Solution

  • Set the default value. Use DataTrigger to handle NULL value case. Override default value in dataTrigger.

    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=Background}"/>
        <Style.Triggers>
             <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=Grid}, Path=Background}" Value="{x:Null}">
                   <Setter Property="Background" Value="CadetBlue"/>
             </DataTrigger>
        </Style.Triggers>
     </Style>