INotifyPropertyChanged property name - hardcode vs reflection?

前端 未结 16 1559
感动是毒
感动是毒 2020-11-28 05:13

What is the best way to specify a property name when using INotifyPropertyChanged?

Most examples hardcode the property name as an argument on the PropertyChanged E

相关标签:
16条回答
  • 2020-11-28 05:40

    Yet another approach: http://www.codeproject.com/Articles/450688/Enhanced-MVVM-Design-w-Type-Safe-View-Models-TVM

    0 讨论(0)
  • Additionally, we found an issue where getting a method name worked differently in Debug vs. Release builds:

    http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/244d3f24-4cc4-4925-aebe-85f55b39ec92

    (The code we were using wasn't exactly reflection in the way you suggested, but it convinced us that hardcoding the property name was the fastest and most reliable solution.)

    0 讨论(0)
  • 2020-11-28 05:42

    Roman:

    I'd say you wouldn't even need the "Person" parameter - accordingly, a completely generic snippet like the one below should do:

    private int age;
    public int Age
    {
      get { return age; }
      set
      {
        age = value;
        OnPropertyChanged(() => Age);
      }
    }
    
    
    private void OnPropertyChanged<T>(Expression<Func<T>> exp)
    {
      //the cast will always succeed
      MemberExpression memberExpression = (MemberExpression) exp.Body;
      string propertyName = memberExpression.Member.Name;
    
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    ...however, I prefer sticking to string parameters with conditional validation in Debug builds. Josh Smith posted a nice sample on this:

    A base class which implements INotifyPropertyChanged

    Cheers :) Philipp

    0 讨论(0)
  • 2020-11-28 05:47

    You might be interessted in this discussion about

    "Best Practices: How to implement INotifyPropertyChanged right?"

    too.

    0 讨论(0)
提交回复
热议问题