c# - 您如何处理 MVVM ViewModel 中的 'SelectedItemChanged' 事件?

标签 c# wpf silverlight mvvm

我有一些逻辑取决于正在设置的两个属性,因为它在两个属性都有值时执行。例如:

private void DoCalc() {
  if (string.IsNullOrEmpty(Property1) || string.IsNullOrEmpty(Property2))
    return;
  Property3 = Property1 + " " + Property2;
}

每次 Property1 或 Property2 更改时都需要执行该代码,但我无法弄清楚如何以风格上可接受的方式执行此操作。以下是我看到的选择:

1) 从ViewModel调用方法

我对此在概念上没有问题,因为逻辑仍在 ViewModel 中 - 我不是“无代码隐藏”纳粹分子。但是,“触发”逻辑(当任一属性更改时)仍在 UI 层中,我不喜欢。代码隐藏看起来像这样:

void ComboBox_Property1_SelectedItemChanged(object sender, RoutedEventArgs e) {
  viewModel.DoCalc();
}

2) 从 Property Setter 调用方法

这种方式看起来最“纯粹”,但也显得丑陋,好像隐藏了逻辑。它看起来像这样:

public string Property1 {
  get {return property1;}
  set {
    if (property1 != value) {
      property1 = value;
      NotifyPropertyChanged("Property1");
      DoCalc();
    }
  }
}

3) Hook 到 PropertyChanged 事件

我现在认为这可能是正确的方法,但在实现 View 模型中 Hook 到属性更改事件感觉很奇怪。它看起来像这样:

public ViewModel() {
  this.PropertyChanged += new PropertyChangedEventHandler(ViewModel_PropertyChanged);
}

void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) {
  if (e.PropertyName == "Property1" || e.PropertyName == "Property2") {
    DoCalc();
  }
}

所以,我的问题是,如果您正在浏览一些具有该要求的源代码,您更希望看到哪种方法被实现(为什么?)。感谢您的任何输入。

最佳答案

我不认为在 setter 中这样做是丑陋的......实际上它可能是你提到的 3 种方法中最好的,因为当你阅读代码时,你会立即看到更改 Property1< 的值Property2 将重新计算 Property3 ;对于其他 2 种方法,这一点都不明显。

但是,我不会使用这些选项。我认为更好的方法是根据 Property1Property2 使 Property3 只读,并在 getter 中计算它的值:

public string Property3
{
    get { return Property3 = Property1 + " " + Property2; }
}

这样,在Property1Property2 的setter 中,您只需要为Property3 调用NotifyPropertyChanged

关于c# - 您如何处理 MVVM ViewModel 中的 'SelectedItemChanged' 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440296/

相关文章:

c# - 在 C# 中使用 NumericComparer 代码,为什么我的 List.Sort() 会出现转换错误?

c# - 将值设置为属性时出现 NullReferenceException

c# - 在 ASP.NET MVC 应用程序中使用 Web.config 而不是 app.config 进行集成测试

c# - Zenject 游戏对象注入(inject)

c# - Caliburn - 子 ViewModel 的 PropertyChanged

wpf - 当前上下文 : strange behaviour 中不存在名称 'InitializeComponent'

c# - 在换行面板中设置最大行数

c# - 自反类型参数约束 : X<T> where T : X<T> ‒ any simpler alternatives?

c# - 在 Windows Phone 7 中,如何在后台线程的 WriteableBitmap 上呈现文本?

wpf - 将 [VisualStateManager] View 状态绑定(bind)到 MVVM View 模型?