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 el开发者_运维问答ements, 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)
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.
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
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.
精彩评论