【问题标题】:WPF MVVM: Add item not present in comboboxWPF MVVM:添加组合框中不存在的项目
【发布时间】:2011-07-19 02:24:49
【问题描述】:

我在 WPF 中使用 MVVM 方法让用户在组合框中选择一项。该模型包含一组可能的选项,组合框绑定到该组,当前选择再次绑定到我的模型的属性。这部分工作正常。

现在我想允许用户在组合框中输入任意文本。如果文本与现有项目不对应,程序应询问他是否要添加新项目。还应该允许他取消操作并选择另一个项目。

我将如何在 MVVM 模式中做到这一点?

【问题讨论】:

    标签: wpf mvvm combobox


    【解决方案1】:

    您可以从 ViewModel 的绑定属性设置器中检查文本的“已存在”状态。此时,您需要一种机制来引发事件并根据发生的情况决定要做什么。

    一个例子:

    enum Outcome { Add, Cancel }
    
    class BlahEventArgs : EventArgs
    {
        Outcome Outcome { get; set; }
    }
    
    class ViewModel
    {
        private string name;
    
        public EventHandler<BlahEventArgs> NotExistingNameSet;
    
        public Name
        {
            get { return this.name; }
    
            set
            {
                if (/* value is existing */) {
                    this.name = value;
                    return;
                }
    
                var handler = this.NotExistingNameSet;
                if (handler == null) {
                    // you can't just return here, because the UI
                    // will desync from the data model.
                    throw new ArgumentOutOfRangeException("value");
                }
    
                var e = new BlahEventArgs { Outcome = Outcome.Add };
                handler(this, e);
                switch (e.Outcome) {
                    case Outcome.Add:
                        // Add the new data
                        this.name = value;
                        break;
                    case Outcome.Cancel:
                        throw new Exception("Cancelled property set");
                }
            }
        }
    }
    

    您的视图将向NotExistingNameSet 添加一个事件处理程序以呈现适当的用户界面并相应地设置e.Outcome 的值。

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 2011-08-19
      • 2013-03-24
      • 2019-04-05
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 2013-01-27
      相关资源
      最近更新 更多