Databound WPF ComboBox with 'New…' item

2019-06-22 01:34发布

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)

3条回答
【Aperson】
2楼-- · 2019-06-22 01:46

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.

查看更多
来,给爷笑一个
3楼-- · 2019-06-22 01:54

Set the ItemsSource property to a CompositeCollection with the new item and bound collection together, then detect that item's selection based on selected index or something similar.

Example Code:

<ComboBox>
   <ComboBox.ItemsSource>
      <CompositeCollection>
         <ComboBoxItem>Add New Item...</ComboBoxItem>
         <CollectionContainer Collection="{Binding Source={StaticResource CollectionSource}}"/>
      </CompositeCollection>
   </ComboBox.ItemsSource>
</ComboBox>

MSDN for CompositeCollection: http://msdn.microsoft.com/en-us/library/system.windows.data.compositecollection(v=vs.110).aspx

查看更多
smile是对你的礼貌
4楼-- · 2019-06-22 01:58

Keep in mind that what you bind to is a UI oriented collection of items which can be different than the business or data entities.

If I were you, I'd insert a 'new' entity in the first position of the bound collection and detect it in my viewmodel to trigger the appropriate action when the user selects it.

查看更多
登录 后发表回答