WPF: how to bind ComboBox ItemsSource in code?

自闭症网瘾萝莉.ら 提交于 2021-01-04 07:17:10

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/6252898/wpf-how-to-bind-combobox-itemssource-in-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!