Adding predefined item to a ComboBox with ItemsSource

蓝咒 提交于 2019-12-20 02:32:59

问题


I'm trying to add a predefined ComboBoxItem into my ComboBox which already has a ItemsSource property set. example:

(Select item)
Item 1
Item 2
Item 3

It's possible to do this without modifying the original items collection?


回答1:


Here is some sample code from MSDN that shows the usage of CompositeCollection:

<ComboBox>
    <ComboBox.ItemsSource>
        <CompositeCollection>
            <ListBoxItem>Please Select</ListBoxItem>
            <CollectionContainer Collection="{Binding Source={StaticResource YOURDATASOURCE}}" />
        </CompositeCollection>
    </ComboBox.ItemsSource>
</ComboBox>

Here are some references to show you the usage of CompositeCollection:

1- http://msdn.microsoft.com/en-us/library/system.windows.data.compositecollection.aspx

2- http://robertbouillon.com/2010/04/17/adding-items-to-a-data-bound-wpf-combobox/

3- How do I convert a ComboBox to use a bound CompositeCollection?




回答2:


If you want to dynamically change the contents of items source, use ObservableCollection instead, so you will have access to Add() method.

private ObservableCollection<string> myStrings;

public MyClass()
{
    myStrings = new ObservableCollection<string>();
    myControl.ItemsSource = myStrings;
}

private void AddNewItem(string item)
{
    myStrings.Add(item);
}


来源:https://stackoverflow.com/questions/13542072/adding-predefined-item-to-a-combobox-with-itemssource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!