开发者

Bind a List<string> to a combobox

I have a list of strings. I wanna populate a combo box with a list of strings. how do I do this? All my tries and searchs are dead end.

i used:

<ComboBox  Name="comboBox2" 开发者_运维百科ItemsSource="{Binding Combobox2items}" />
 public partial class EditRule : Window
{
    public ObservableCollection<string> Combobox2items { get;  set; }

    public EditRule()
    {
        InitializeComponent();
        Combobox2items = new ObservableCollection<string>();
    Combobox2items.Add("DFd");

    }}

EDIT: adding Combobox2items.ItemsSource = Combobox2items; works, but why ItemsSource="{Binding Combobox2items}" doesn't?


You can popuplate a ComboBox, in fact every ItemsControl, in 2 Ways.

First: Add directly Items to it, which works in Code or in Xaml

<ComboBox>
    <ComboBoxItem Name="Item1" />
    <ComboBoxItem Name="Item2" />
</ComboBox>

but this is rather static. The second approach uses a dynamic list.

As an example, lets assume you have a window and a combobox in your xaml. The Combobox gets x:Name="myCombobox"

In your code behind you can create your List and set it as an ItemsSource

List<string> myItemsCollection = new List<string>();
public Window1()
{
   InitializeComponent();
   myItemsCollection.Add("Item1");
   myCombobox.ItemsSource = myItemsCollection;
}

this works fine, but has one problem. If you change the List after you set it as an ItemsSource, the UI will not catch up with the newest change. So to make that work aswell, you need to use an ObservableCollection now the collection can notify any changes, which the UI will listen to. and automatically add the new item to the combobox.


Any list-based control in WPF has an ItemsSource property that you can assign or bind a list to. In code:

comboBox1.ItemsSource = myList;

... or if your list is a property on an object which is the DataContext for your Window:

<ComboBox ItemsSource="{Binding MyList}" />


Use ObservableCollection<string> instead of List<string>, it implements INotifyCollectionChanged for you

ObservableCollection Class

WPF provides the ObservableCollection class, which is a built-in implementation of a data collection that implements the INotifyCollectionChanged interface

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜