2013-11-26 59 views
2

我有以下方法:安全订阅的PropertyChanged

void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    switch (e.PropertyName) 
    { 
     case "InitializeFailureMessage": 
      if (Vm.InitializeFailureMessage != null) 
       ShowInitializeFailure(Vm.InitializeFailureMessage); 
      break; 
    } 
} 

刚才的方法有一个bug:以前被称为InitializeFailureErrorMessage的财产,当它被重命名,没有一个更新的这个字符串处理程序。

是否有更好,更容易出错的方式来订阅PropertyChanged事件?发射事件时,我们现在可以使用[CallerMemberName]。执行处理程序时是否有类似的技巧?

回答

1

使用this实用方法来获得使用Expressions.

考虑这个属性名就是你的类触发事件,引入static readonly string field告诉财产的字符串表示。然后使用该静态字段来检查哪个属性已更改。

class MyClass 
{ 
    public static readonly string InitializeFailureMessageProperty = GetPropertyName(() => x.InitializeFailureMessageProperty);//x can be a dummy instance. 
} 

void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    if (e.PropertyName == MyClass.InitializeFailureMessageProperty) 
    { 
     if (Vm.InitializeFailureMessage != null) 
      ShowInitializeFailure(Vm.InitializeFailureMessage); 
    } 
} 
+0

好的建议,谢谢。使用静态只读字符串的技巧有时可能会有用,因为表达式会带来一些性能开销。 – Oliver

+0

@Oliver是的,这就是为什么我选择在应用程序域中最多只发生一次的“静态只读”。 :) –

+0

@Oliver你真的会注册这么多,经常这样表达开销是如此的担忧吗? – Euphoric

2

快速使用扩展方法,表达和思想的代表:

public static class Extension 
{ 
    public static void RegisterNotify<T>(this T obj, Expression<Func<T, object>> propExpr, Action action) where T : INotifyPropertyChanged 
    { 
     string name = GetPropertyName(propExpr); 
     obj.PropertyChanged += (s, e) => { if (e.PropertyName == name) action() }; 
    } 
} 

,它被称为像:

Notifier obj = new Notifier(); // implements INotifyPropertyChanged 
    obj.RegisterNotify(x => x.Property,() => { /* do something when Property changes */ }); 
    obj.RegisterNotify(x => x.Property2,() => { /* do something else when Property2 changes */ }); 
+0

如果我们有两个属性呢?那会订两次是不是? –

+0

@SriramSakthivel是的,这是一个问题吗?我认为这不会对性能产生任何重大影响,除非您注册很多属性并且经常打电话给他们。 – Euphoric

+0

是的,**绝对**有问题。执行时,所有操作都会执行多次。考虑'{account.Balance - = 10;}'作为一个动作。这将执行多次你订阅这不是预期的行为。旁注:虽然这可以很容易地修复。 –