我需要WPF下的Style
,在多个条件满了时设置几个属性。但是,我的一个条件是Not Equal To
类型。我应该如何更改以下Style
以使条件成为Not Equal To
?是否可以在没有IValueConverter
的情况下实现?
<Style>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!--<Condition 1 here.../>-->
<!--<Condition 2 here.../>-->
<Condition Binding="{Binding Path=id}" Value="3"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
我需要以下内容,但这当然不起作用,因为Triggers仅支持Equal
运算符。
<Style>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!--<Condition 1 here.../>-->
<!--<Condition 2 here.../>-->
<Condition Binding="{Binding Path=id}" Value<>"3"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
答案 0 :(得分:11)
您需要IValueConverter
和一些额外的标记:
<Style>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!--<Condition 1 here.../>-->
<!--<Condition 2 here.../>-->
<Condition>
<Condition.Binding>
<Binding Path="id" Converter="{StaticResource ValueToEqualsParameterConverter}">
<Binding.ConverterParameter>
<System:Int32>3</System:Int32>
</Binding.ConverterParameter>
</Binding>
</Condition.Binding>
<Condition.Value>
<System:Boolean>False</System:Boolean>
</Condition.Value>
</Condition>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="Black" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
转换器:
public class ValueToEqualsParameterConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
return value == parameter;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
return null;
}
}
答案 1 :(得分:0)
另一种选择是将默认值定义为样式中的setter,然后实现数据触发器。在以下代码中,背景值始终为红色,除非值为3
<Style>
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Black"/>
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<!--<Condition 1 here.../>-->
<!--<Condition 2 here.../>-->
<Condition Binding="{Binding Path=id}" Value="3"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="DefaultColor"/>
<Setter Property="Foreground" Value="DefaultColor2"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
&#13;