Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databound WPF ComboBox with 'New...' item

Hi all
I have a combobox which is databound to a list of elements. But in addition to that list of elements, i want to have another item. This item should display the text 'New...'
The idea is if they select one of the normal elements, it performs some action involving that element. If they select the 'New' element, it will take them to a screen where they can create a new item.
The problem is, When you databind something you dont get the option to add another item to it, and there is no question of adding a dummy item to the list of elements...

Is this an opportunity to create a new control based on the ComboBox which has a 'DefaultElement' property? (with all of the associated templating and command binding etc)

like image 651
TerrorAustralis Avatar asked Oct 26 '10 09:10

TerrorAustralis


1 Answers

To do this I have previously created a dummy wrapper class for the normal type, allowing you to bind to a list containing mostly the correct values and also your "New..." one, e.g.

public class DisplayClass
{
    public DisplayClass(ModelClass mc)
    {
         this.mc = mc;
    }

    public string Name
    {
        get { return this.mc != null ? this.mc.Name : "New..."; }
    }

    public bool IsDummy
    {
        return this.mc == null;
    }

    public ModelClass Model
    {
        return this.mc;
    }
}

You can then host a collection of these in your data context (ViewModel), and handle the selection appropriately based on IsDummy. It's not as automatic as a control with this functionality built in, but is pretty simple and could probably easily be made generic and so reusable.

like image 134
Simon Steele Avatar answered Sep 25 '22 15:09

Simon Steele