开发者

WPF MVVM: Add item not present in combobox

开发者 https://www.devze.com 2023-02-18 09:20 出处:网络
I\'m using a MVVM approach with WPF to let the user select one item in a combo开发者_JAVA技巧box. The model contains a set of possible options, the combobox is bound to this set, the current selection

I'm using a MVVM approach with WPF to let the user select one item in a combo开发者_JAVA技巧box. The model contains a set of possible options, the combobox is bound to this set, the current selection is again bound to a property of my model. This part works fine.

Now I'd like to allow the user to enter an arbitrary text into the combobox. If the text doesn't correspond to an existing item the program should ask him if he wants to add a new item. He should also be allowed to cancel the action and select another item.

How would I do that within the MVVM pattern?


You would check the "already existing" status of the text from your ViewModel's bound property setter. At that point, you need a mechanism to raise an event and decide what to do based on what happens.

An example:

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");
            }
        }
    }
}

Your View would add an event handler to NotExistingNameSet to present appropriate UI and set the value of e.Outcome accordingly.

0

精彩评论

暂无评论...
验证码 换一张
取 消