PropertyChangedTrigger对于多个属性?

时间:2015-04-22 18:53:54

标签: wpf

为了冗余起见,是否有办法为所有共享相同条件的多个属性创建PropertyChangedTrigger,而不为每个PropertyChangedTrigger重复指定条件?

例如,当PropertyA,PropertyB和PropertyC发生变化时,我想要一个命令在我的ViewModel中执行。

1 个答案:

答案 0 :(得分:0)

我在考虑扩展PropertyChangedClass并添加一个可观察的Bindings集合的依赖属性。但事实证明,我对如何监控Bindings知之甚少。

然后我看到了一些旧代码并看到了Multibinding。我认为它可行。它使用MultiValueConverter,只增加静态字段。我不确定这是否是最佳解决方案,但这有效。

首先是MultiValueConverter:

public class IncrementOnPropertyChangedMultiConverter:IMultiValueConverter
{
static uint _counter=0;
#region IMultiValueConverter Members

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
  _counter = _counter < uint.MaxValue ? _counter + 1 : 0;
  return _counter;
}

public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
  throw new NotImplementedException();
}

#endregion
}

然后在XAML中,你只需在PropertyChangedTrigger中添加一个MultiBinding而不是Binding。

<i:Interaction.Triggers>
    <ei:PropertyChangedTrigger>
        <ei:PropertyChangedTrigger.Binding>
            <MultiBinding Converter="{StaticResource IncrementOnPropertyChangedMultiConverter}">
                <Binding Path="Property1" />
                <Binding Path="Property2" />
                <Binding Path="PropertyN" />
            </MultiBinding>
        </ei:PropertyChangedTrigger.Binding>
        <i:Interaction.Behaviors>
            <ei:ConditionBehavior>
                <ei:ConditionalExpression>
                    <ei:ComparisonCondition LeftOperand="{Binding Property1}"
                                            Operator="Equal"
                                            RightOperand="{Binding Property2}" />
                </ei:ConditionalExpression>
            </ei:ConditionBehavior>
        </i:Interaction.Behaviors>
        <ei:ChangePropertyAction PropertyName="Background"
                                 Value="Transparent" />
    </ei:PropertyChangedTrigger>
<i:Interaction.Triggers>
相关问题