Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to addComboBox Items dynamically in wpf

Tags:

c#

wpf

I am new to WPF ,

I am adding items dynamically to a combobox like below

   objComboBox.Items.Add("<--Select-->");

Now i need to set value & index for the particular item . In asp.net i was doing

DropDownList1.Items.FindByText("<--Select-->").Value ="-1" 

I ma not finding appropriate method in wpf . how can iI do this?

like image 639
Kuntady Nithesh Avatar asked Dec 28 '11 09:12

Kuntady Nithesh


2 Answers

XAML:

<ComboBox ItemsSource="{Binding cbItems}" SelectedItem="{Binding SelectedcbItem}"/>

Code-behind:

public ObservableCollection<ComboBoxItem> cbItems { get; set; }
public ComboBoxItem SelectedcbItem { get; set; }

public MainWindow()
{
    InitializeComponent();
    DataContext = this;

    cbItems = new ObservableCollection<ComboBoxItem>();
    var cbItem = new ComboBoxItem { Content = "<--Select-->" };
    SelectedcbItem = cbItem;
    cbItems.Add(cbItem);
    cbItems.Add(new ComboBoxItem { Content = "Option 1" });
    cbItems.Add(new ComboBoxItem { Content = "Option 2"});
}
like image 68
snurre Avatar answered Oct 05 '22 23:10

snurre


Always try to avoid accessing the UI directly. Use a binding to bind data to your control and add, search, remove whatever... only on data. To change a UI will take care of WPF binding itself.

An example: http://www.codeproject.com/KB/WPF/DataBindingWithComboBoxes.aspx

like image 23
Tigran Avatar answered Oct 05 '22 23:10

Tigran