c# - 自己订阅 PropertyChanged 或 setter 中的添加方法调用?

标签 c# wpf mvvm inotifypropertychanged

也许这里已经有这样的问题了,但我没有找到。

我有 MVVM 应用程序,在我的 ViewModel 中,我必须对某些属性的更改执行一些额外的操作(例如,如果 View 更改它们)。您认为哪种方法更好,为什么?

1st - 添加 AdditionalAction 对 setter 的调用

public class ViewModel: INotifyPropertyChanged
{
  private int _MyProperty;

  public int MyProperty
  {
    get { return _MyProperty; }
    set
    {
      if (_MyProperty == value) return;
      _MyProperty = value;
      RaisePropertyChanged(() => MyProperty);

      // --- ADDITIONAL CODE ---
      AdditionalAction();
    }
  }
}

2nd - 自行订阅 INotifyPropertyChanged

public class ViewModel: INotifyPropertyChanged
{
  public ViewModel()
  {
    // --- ADDITIONAL CODE ---
    PropertyChanged += OnPropertyChanged;
  }

  private int _MyProperty;

  public int MyProperty
  {
    get { return _MyProperty; }
    set
    {
      if (_MyProperty == value) return;
      _MyProperty = value;
      RaisePropertyChanged(() => MyProperty);
    }
  }

  void PropertyChanged(object sender, PropertyChangedEventArgs e)
  {
    // --- ADDITIONAL CODE ---
    if (e.PropertyName == "MyProperty")
      AdditionalAction();
  }
}

想象一下,我没有性能问题或 10'000 个对象。它只是 View 和 ViewModel。什么是更好的?第一个代码“更小”并且开销更少,但第二个(在我看来)更清晰,我可以将代码片段用于自动生成属性的代码。甚至更多——在第二种情况下,我可以在事件处理程序中编写如下内容:

On.PropertyChanged(e, p => p.MyProperty, AdditionalAction);

On 是类助手。

那么,您认为什么更好,为什么?

更新:

好的,看来我找到了一种方法:

3 - 在 RaisePropertyChanged 中添加“扩展点”:

public class NotificationObject : INotifyPropertyChanged
{
  void RaisePropertyChanged(Expression<...> property)
  {
    // ... Raise PropertyChanged event
    if (PropertyChanged != null)
      // blah-blah

    // Call extension point
    OnPropertyChanged(property.Name);
  }

  public virtual OnPropertyChanged(string propertyName)
  {
  }
}

public class ViewModel: NotificationObject
{
  private int _MyProperty;

  public int MyProperty
  {
    get { return _MyProperty; }
    set
    {
      if (_MyProperty == value) return;
      _MyProperty = value;
      RaisePropertyChanged(() => MyProperty);
    }
  }

  override OnPropertyChanged(string propertyName)
  {
    if (propertyName == "MyProperty")
      AdditionalAction();
  }
}

这样我们就不用事件了,但是所有的“附加 Action ”都是从同一个“扩展点”调用的。 “所有添加操作都放在一个地方”比“不透明的工作流程”好吗?

最佳答案

绝对会选择第一种方法:

  • 很清楚
  • 它的流程和意图是明确的
  • 它避免了奇怪的(imo) self 订阅

第二种情况的“好处”是让您可以使用自动生成的属性,这与第一种情况的执行流程的清晰度不相符,imo。

希望这对您有所帮助。

关于c# - 自己订阅 PropertyChanged 或 setter 中的添加方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10450952/

相关文章:

c# - 我如何测试素数?

xaml - MVVM - 摘要/详细信息

c# - 不同View的ViewModel Initialize方法

c# - 对象的未引用与引用使用

c# - 小数精度 - C#

c# - 在同一主机和端口下运行多个应用程序

wpf - 制作 TextBox PlaceholderText 换行

c# - 无需单击安装新版本按钮即可在无人服务器上自动更新 ClickOnce

c# - 如果从 pendrive 或服务器执行 Entity Framework 失败

javascript - 如何从剑道模板绑定(bind)调用父方法?