【问题标题】:WPF DataBinding with Constructor带有构造函数的 WPF 数据绑定
【发布时间】:2011-02-28 22:52:38
【问题描述】:

(对于本例)ListBox l 绑定到 CustomObjectCollection c。

我会调用 c 的构造函数吗?

如果 c 是通用对象怎么办?

**In XAML (1)**
<ListBox Content={Binding CustomObjectCollection}/>

**In Codebehind**
CustomObjectCollection<MyClass> c;
**In XAML (2)**
<ListBox Content={Binding CustomObjectCollection}/>

假设在c,我填充集合(动态,使用构造函数)
哪个绑定会调用构造函数?

对不起,如果不清楚,我不知道如何解释。

【问题讨论】:

  • 这个问题不是很清楚。你想达到什么目的?您可以发布您的 XAML/代码隐藏吗?

标签: wpf generics data-binding collections listbox


【解决方案1】:

您应该绑定到一个属性。如果需要构建源对象,则必须在后面的代码中完成。

<ListBox ItemsSource={Binding ListSource} />

//Codebehind
class MyControl : UserControl {
    public CustomObjectCollection ListSource {get; private set;}

    public MyControl() {
      ListSource  = new CustomObjectCollection (/*arguments*/);
      InitializeComponent();
      DataContext = this;
    }
}

【讨论】:

    【解决方案2】:

    几件事:

    1. 您只能绑定到公共属性。看来您已将 c 声明为成员变量,但不是属性。所以这个绑定不会成功。
    2. 无法在ListBox 上使用Content 属性进行绑定。我认为使用 ItemsSource 属性可以更好地完成您想要做的事情。查看 MSDN 上链接的示例;这应该可以帮助您入门。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多