开发者

WPF DataBinding with Constructor

(For this example) ListBox l is bound to CustomObjectCollection c.

Does l call c's Constructor?

What if c is a Generic Object?

**In XAML (1)**

<ListBox Content={Binding CustomObj开发者_JAVA技巧ectCollection}/>

**In Codebehind**

CustomObjectCollection<MyClass> c;

**In XAML (2)**

<ListBox Content={Binding CustomObjectCollection}/>

Suppose in c, I populate the collection(dynamically, using the constructor)

Which binding would call the constructor?

Sorry if this is unclear, I have no idea how to explain it.


You should bind to a property. If the source object needs to be constructed, then it has to be done in the code behind.

<ListBox ItemsSource={Binding ListSource} />

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

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


A couple things:

  1. You can only bind to public properties. It appears you have c declared as a member variable, but not a property. So this binding will not succeed.
  2. There is no way to bind using a Content property on ListBox. I think what you are trying to do is better accomplished using the ItemsSource property. Check out the example linked on MSDN; that should get you started.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜