【问题标题】:How do you set binding of ComboBox ItemsSource in UserControl?如何在 UserControl 中设置 ComboBox ItemsSource 的绑定?
【发布时间】:2012-09-06 18:20:38
【问题描述】:

这是我的 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 中。

【问题讨论】:

  • 您为什么要同时在 XAML 和代码后面设置绑定?
  • 确保不要在本地更改 ItemsSource 的值,否则会使绑定无效。除此之外,您的代码似乎还不错。查看 VisualStudio 中的输出窗口,它给您的绑定错误是什么?
  • @B-Rad 我的answer here 对您有帮助吗? :D

标签: c# wpf binding


【解决方案1】:

你可以试试(替换这个)

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);

【讨论】:

【解决方案2】:

您需要设置包含您的属性 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);  

(通过手机发帖)

【讨论】:

【解决方案3】:

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

我将在 .xaml 文件保存后序列化绑定。这似乎工作得很好。不再需要在代码中设置绑定。

【讨论】:

    猜你喜欢
    • 2018-11-08
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2014-12-10
    相关资源
    最近更新 更多