WPF: how to bind ComboBox ItemsSource in code?

newman picture newman · Jun 6, 2011 · Viewed 9.8k times · Source

I need to convert this following XAML into code-behind:

<ComboBox SelectedItem="{Binding Level}" ItemsSource="{Binding Levels}" />

However, this code doesn't compile:

new ComboBox() { SelectedItem = new Binding("Level"), ItemsSource = new Binding("Levels") }

The error: "Cannot implicitly convert type 'System.Windows.Data.Binding' to 'System.Collections.IEnumerable'. An explicit conversion exists (are you missing a cast?)". How do I cast?

Answer

HCL picture HCL · Jun 6, 2011
ComboBox cbo=new ComboBox();
cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding("Level"){ /* set properties here*/});
cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding("Levels"));
....