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?
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"});
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With