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)
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:
- 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. - There is no way to bind using a
Content
property onListBox
. I think what you are trying to do is better accomplished using theItemsSource
property. Check out the example linked on MSDN; that should get you started.
精彩评论