2015-04-22 109 views
0

有沒有辦法爲多個屬性創建PropertyChangedTrigger,它們都共享相同的條件,爲了冗餘,而不必爲每個PropertyChangedTrigger重複指定條件?PropertyChangedTrigger對於多個屬性?

例如,當PropertyA,PropertyB和PropertyC發生變化時,我想要在我的ViewModel中執行一個命令。

回答

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。

<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>