使用MVVM取消wpf中的组合框中的选择

时间:2013-01-02 12:28:30

标签: wpf mvvm combobox

我有一个List类型的组合框。我有通过datacontext绑定的ItemsSource和ItemSelected。如果所选项目已更改,则会显示一条确认用户操作的弹出消息。单击“确定”后,选择将更改。但是在点击取消时,应该取消选择并保留先前的项目。下面是绑定到组合框的SelectedItem的属性。

Public SomeClass Sel
{
  get
  {
    return _sel;
  }
  set
  {
    if (_sel != value)
    {
      var sview = _sel;

      if (Compare())
      {
        _sel = value;

        if (Sel != null)
          IsDefault = Sel.IsDefault;
        OnPropertyChanged(() => Sel);
      }
      else
      {
        MessageBoxResult result = MessageBox.Show("Message.", "Owb Message", MessageBoxButton.OKCancel);
        if (result == MessageBoxResult.OK)
        {
          _sel = value;
          if (Sel != null)
            IsDefault = Sel.IsDefault;
          OnPropertyChanged(() => Sel);
        }
        else
        {
          Application.Current.Dispatcher.BeginInvoke(new Action(() =>
          {
            _sel = sview;
            OnPropertyChanged("Sel");
          }), DispatcherPriority.Send, null);
          return;
        }
      }
    }
  }
}

组合框位于弹出窗口中。那么Dispatcher对象在那种情况下会起作用吗?

3 个答案:

答案 0 :(得分:1)

我猜测保留了选定的值 ,但View无法正确更新。

看一下这篇文章:http://www.codeproject.com/Articles/407550/The-Perils-of-Canceling-WPF-ComboBox-Selection。基本上,.Net 3.5中确实存在的一些解决方法不再适用于.Net 4.0 ..

答案 1 :(得分:0)

作为一般规则,如果您的视图控件泄漏到视图模型中,那么您将走上一条不想失去的路径。

创建一个拦截ComboBox的OnChanged事件并启动消息框的行为。这是关于using behaviours

的教程

这样可以保留UI中的所有UI逻辑,并使您的viewmodel保持管理数据和验证。

答案 2 :(得分:0)

现在就像魔术一样!我在调用调度程序之前错过了设置值。     _sel = sview

相关问题