How to add ComboBox elements dynamically in wpf

I'm new to WPF,

I add elements dynamically to combobox as shown below

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

Now I need to set the value and index for a specific item. In asp.net I did

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

I did not find a suitable method in wpf. How can i do this?

+4
source share
4 answers

XAML:

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

Code for:

 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"}); } 
+14
source

Always try to avoid direct access to the user interface. Use binding to bind data to your control and add , search , remove independently ... only for data . To change the user interface, we will take care of WPF binding.

Example: http://www.codeproject.com/KB/WPF/DataBindingWithComboBoxes.aspx

+4
source
  combo.SelectedIndex = combo.Items.IndexOf("<--Select-->"); 

But it is better to use Binding, as mentioned by snurre

+1
source

If it is first listed, you should use: objComboBox.SelectedIndex = 0; or DropDownList1.SelectedIndex = 0;

If this is not the first, use: objComboBox.SelectedItem = "<- Select โ†’"; or DropDownList1.SelectedItem = "<- Select โ†’";

0
source

Source: https://habr.com/ru/post/1388263/


All Articles