5

How to trigger an action in WPF when the Property is not null? This is a working solution when is null:

<Style.Triggers>
    <DataTrigger Binding="{Binding}" Value="{x:Null}">

      <Setter Property="Background" Value="Yellow" />

    </DataTrigger>
</Style.Triggers>

I know that you cant "turn around" the condition and do what you need, but want to know

PaN1C_Showt1Me
  • 11,483
  • 28
  • 90
  • 148

3 Answers3

10

Unfortunately, you can't. But actually it's not necessary : you just need to specify the background for when the value is not null in the style setters, not in the trigger :

<Style.Setters>
    <!-- Background when value is not null -->
    <Setter Property="Background" Value="Blue" />
</Style.Setters>
<Style.Triggers>
    <DataTrigger Binding="{Binding}" Value="{x:Null}">

      <Setter Property="Background" Value="Yellow" />

    </DataTrigger>
</Style.Triggers>
Thomas Levesque
  • 270,447
  • 59
  • 580
  • 726
8

You can use DataTrigger class in Microsoft.Expression.Interactions.dll that come with Expression Blend.

Code Sample:

<i:Interaction.Triggers>
    <ie:DataTrigger Binding="{Binding YourProperty}" Value="{x:Null}" Comparison="NotEqual">
       <ie:ChangePropertyAction PropertyName="YourTargetPropertyName" Value="{Binding YourValue}"/>
    </ie:DataTrigger>
</i:Interaction.Triggers>

Using this method you can trigger against GreaterThan and LessThan too. In order to use this code you should reference two dll's:

System.Windows.Interactivity.dll
Microsoft.Expression.Interactions.dll

And add the corresponding namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  
xmlns:ie="http://schemas.microsoft.com/expression/2010/interactions"
pogosama
  • 1,416
  • 18
  • 26
yossharel
  • 1,709
  • 2
  • 22
  • 29
0

it is an old question, but I want to answer. Actually you can. Just you have to use Converter in binding. Converter must return is null or not. So you will check statement is true or false. It provide you can check two condition if return value is false, it means it is not null. If it is true, it means it is null.

<converters:IsNullConverter x:Key="IsNullConverterInstance"/>

<Style>
<Style.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=DataContext, Converter={StaticResource IsNullConverterInstance}" Value="True">    
      <Setter Property="Background" Value="Yellow" />    
    </DataTrigger>
</Style.Triggers></Style>


    public class IsNulConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        return value == null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {

        return Binding.DoNothing;
    }
}
Doctor
  • 698
  • 8
  • 12