Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a List<string> to a combobox

Tags:

c#

wpf

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?

like image 376
Nahum Avatar asked Dec 01 '22 07:12

Nahum


1 Answers

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.

like image 57
dowhilefor Avatar answered Dec 02 '22 21:12

dowhilefor