【问题标题】:WPF: how to bind ComboBox ItemsSource in code?WPF:如何在代码中绑定 ComboBox ItemsSource?
【发布时间】:2011-06-06 13:42:14
【问题描述】:

我需要将以下 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'。存在显式转换(您是否缺少强制转换?)”。如何投射?

【问题讨论】:

    标签: wpf binding itemssource


    【解决方案1】:
    ComboBox cbo=new ComboBox();
    cbo.SetBinding(ComboBox.SelectedItemProperty,new Binding("Level"){ /* set properties here*/});
    cbo.SetBinding(ComboBox.ItemsSourceProperty,new Binding("Levels"));
    ....
    

    【讨论】:

    • 非常感谢。您的意思一定是“ComboBox.ItemsSourceProperty”而不是“ComboBox.ItemsProperty”(因为我找不到这样的),对吧?否则,它工作正常。但是你能解释一下为什么吗?如何按照错误消息中的要求进行投射?我需要使那个(转换)工作,因为我还需要为没有 SetBinding 方法的 DataGridComboBoxColumn 设置 ItemsSource 绑定。
    • @miliu:我已经纠正了错误 - 谢谢。将 ItemsControl.ItemsSourceProperty 用于 DataGridComboBoxColumn。但是有一个很大的警告:DataGridComboBoxColumn 不属于可视化树的一部分,因此,定义 Bindings 有点棘手。谷歌“DataGridComboBoxColumn and Binding”,那么你可能会得到很多关于这个的帖子。您可以使用以下代码为任何 DependencyProperty 设置绑定:BindingOperations.SetBinding(yourDataGridCbo, dependencyProperty, binding);
    • 谢谢一百万!我无法使用 DataGridComoBoxColumn 使其工作,但我使用 DataGridTemplateColumn 使其工作。
    猜你喜欢
    • 2015-04-07
    • 2015-11-16
    • 2018-11-08
    • 2011-02-27
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多