WPF Trigger not null

前端 未结 3 561
深忆病人
深忆病人 2021-02-06 14:49

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

         


        
相关标签:
3条回答
  • 2021-02-06 15:16

    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;
        }
    }
    
    0 讨论(0)
  • 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>
    
    0 讨论(0)
  • 2021-02-06 15:28

    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"
    
    0 讨论(0)
提交回复
热议问题