【问题标题】:Input validation in WPFWPF 中的输入验证
【发布时间】:2010-06-14 02:14:53
【问题描述】:

我正在使用 MVVM 设计模式在 wpf 中开发应用程序。当一个项目被选中时我有一个列表框,然后一个对话框打开,在可编辑模式下具有相同的记录。此对话框与列表中的选定项目绑定。我已经使用 IDataErrorInfo 为文本框应用了验证规则。当用户更新对话框上的记录时,每次按键时,列表框中的选定记录也会更改。如果用户按下保存按钮,那么我将更改提交到数据库。但是如果用户单击取消按钮,那么我不会提交对数据库的更改,但列表框会使用 GUI 中的当前更新进行更新。当我刷新列表时,旧值再次出现。我的要求是仅在用户点击保存按钮时更新列表框,而不是在对话框上的每次按键时更新列表框。我首先用 linq to sql 类填充通用列表,然后将列表框与它绑定。请让我知道我必须做什么。

提前致谢

【问题讨论】:

    标签: wpf input validation


    【解决方案1】:

    问题是您在两个表单上编辑同一个对象。您应该将 SelectedItem 传递给对话框表单,然后重新查询数据库以获取传递给构造函数的项目。这有两件事:允许您在编辑对象时取消更改,并为用户提供数据库中的最新数据。

    这样想...如果列表框包含的数据甚至是几分钟前的数据,那么您的用户将修改可能已经被另一个运行您的应用程序的用户更改的数据。

    一旦用户在对话框表单中保存(或删除)记录,您就必须刷新列表框。通常我使用以下方法:

    DialogViewModel:

    // Constructor
    public DialogViewModel(MyObject myObject)
    {
        // Query the database for the required object
        MyObject = (from t in _dc.MyObjects where t.ID == myObject.ID 
                   select t).Take(1).Single();
    }
    
    // First define the Saved Event in the Dialog form's ViewModel:
    public event EventHandler Saved;
    public event EventHandler RequestClose;
    
    // Raise the Saved handler when the user saves the record
    // (This will go in the SaveCommand_Executed() method)
       EventHandler saved = this.Saved;
       if (saved != null)
           saved(this, EventArgs.Empty);
    

    列表框视图模型

    Views.DialogView view = new Views.DialogView();
    DialogViewModel vm = new DialogViewModel(SelectedItem);  // Pass in the selected item
    
    // Once the Saved event has fired, refresh the 
    // list of items (ICollectionView, ObservableCollection, etc.)
    // that your ListBox is bound to
    vm.Saved += (s, e) => RefreshCommand_Executed();
    vm.RequestClose += (s, e) => view.Close();
    view.DataContext = vm;
    view.ShowDialog();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 2012-10-11
      相关资源
      最近更新 更多