WPF:如何在代码中绑定ComboBox ItemsSource?

时间:2011-06-06 13:42:14

标签: wpf binding itemssource

我需要将以下XAML转换为代码隐藏:

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

但是,此代码无法编译:

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

错误:“无法将类型'System.Windows.Data.Binding'隐式转换为'System.Collections.IEnumerable'。存在显式转换(您是否错过了转换?)”。我该如何演员?

1 个答案:

答案 0 :(得分:3)

ComboBox cbo=new ComboBox();
cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding("Level"){ /* set properties here*/});
cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding("Levels"));
....