如何在UserControl中设置ComboBox ItemsSource的绑定?

时间:2012-09-06 18:20:38

标签: c# wpf binding

这是我的UserControl中的组合框:

<Combobox ItemsSource="{Binding ComboItemsProperty}" />

我试过了:

Binding bind = new Binding();
bind.Mode = BindingMode.OneWay;
bind.Source = this;
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBinding(ComboBox.ItemsSourceProperty, bind);

然而,这不起作用。我想我正在做bind.Source错误,但我不确定将Source设置为什么。这段代码在我的UserControl.xaml.cs中。

3 个答案:

答案 0 :(得分:0)

您可以尝试(替换此项)

Binding bind = new Binding();
bind.Mode = BindingMode.OneWay;
bind.Source = yourCollectionSourceOrClass; //<--Replace with your collection
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBinding(ComboBox.ItemsSourceProperty, bind);

答案 1 :(得分:0)

您需要包含属性 ComboItemsProperty 的实例的设置上下文。因此,应该将它设置为'this.DataContext'或包含您已定义的ItemSource属性的其他类对象实例,而不是'this'。

试试这个,

Binding bind = new Binding();  
bind.Mode = BindingMode.OneWay;  
bind.Source = this.DataContext;  
bind.Path = new PropertyPath("ComboItemsProperty");  
this.SetBinding( ComboBox. ItemsSource Property, bind);  

(发布frm mobile)

答案 2 :(得分:0)

我已经尝试了很多方法来做到这一点,但是,似乎没有任何工作。

当我将.xaml文件保存出来时,我将序列化绑定。这似乎完美无缺。不再需要在代码中设置绑定。

相关问题