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

标签 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”。存在显式转换(是否缺少强制转换?)”。我该如何转换?

最佳答案

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

关于WPF:如何在代码中绑定(bind)ComboBox ItemsSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6252898/

相关文章:

c# - 在 CollectionViewSource 的筛选期间保留 SelectedItem

c# - 使用 StaticResource 中的 ItemsSource 将命令绑定(bind)到 Viewmodel

c# - 一次移动两个 WPF 窗口?

xml - 如何指定 XmlAccessorType 用于 JAXB xjc 生成的类

wpf - 托管的Winform控件不响应来自WPF的事件

c# - 在运行时添加属性

datatable - WPF BindingListCollectionView 到 ListCollectionView(数据表作为 ItemsSource)

c# - 在 MultiBinding 中使用另一个元素的 ItemsSource 属性

c# - 如何从其 Click 事件 WPF 中停止按钮命令的执行

c# - 在 WPF 中测量运行时创建的控件