WPF:如何在代码中绑定ComboBox ItemsSource? [英] WPF: how to bind ComboBox ItemsSource in code?
本文介绍了WPF:如何在代码中绑定ComboBox ItemsSource?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将以下XAML转换为隐藏代码:
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") }
错误:无法将类型'System.Windows.Data.Binding'隐式转换为'System.Collections.IEnumerable'.存在显式转换(您是否需要强制转换?)".我该如何投射?
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?
推荐答案
ComboBox cbo=new ComboBox();
cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding("Level"){ /* set properties here*/});
cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding("Levels"));
....
这篇关于WPF:如何在代码中绑定ComboBox ItemsSource?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文