DataTriggerBehavior不适用于空值

时间:2016-05-20 09:13:48

标签: c# xaml uwp

如果value为null,我试图将stackpanel的可见性设置为折叠,但DataTriggerBehavior不会更改它的可见性值,如果我将值更改为其他工作的值,则下面是xaml:

 <Interactivity:Interaction.Behaviors>
     <Core:DataTriggerBehavior Binding="{Binding Name}"
                                 Value="{x:Null}">
     <Core:ChangePropertyAction TargetObject="{Binding ElementName=spName}"
                                 PropertyName="Visibility"
                                 Value="Collapsed" />
                    </Core:DataTriggerBehavior>
 </Interactivity:Interaction.Behaviors>

1 个答案:

答案 0 :(得分:1)

一种选择是使用一个简单的转换器,假设NameString,如果值为null则返回一个空字符串,否则返回值为String

public class NullToEmptyStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)            
            return "";            
        else
            return value.ToString();
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

你的xaml将引用NullToEmptyStringConverter NB local是我创建转换器类的命名空间,它可能在你的应用程序中有所不同

<Page.Resources>
    <local:NullToEmptyStringConverter x:Key="NullToEmptyStringConverter"/>
</Page.Resources>

和您的DataTrigger

<Interactivity:Interaction.Behaviors>
 <Core:DataTriggerBehavior Binding="{Binding Name, Converter={StaticResource NullToEmptyStringConverter}}"
                             Value="">
     <Core:ChangePropertyAction TargetObject="{Binding ElementName=spName}"
                             PropertyName="Visibility"
                             Value="Collapsed" />
 </Core:DataTriggerBehavior>