Beware, this is a rather basic question (I think).
I have a UserControl, called MyUserControl. I use it in a DataTemplate for my ListBox:
<l:MyUserControl DataContext="Test" />
Now I want to access this DataContext in the code-behind of MyUserControl, and I expect DataContext to contain a string object with contents "Test". However, DataContext is null. What am I missing here?
-
You need some field or propertie in MyUserControl's class named DataContext.
See here to learn about user control properties in .net.
Robbert Dam : UserControl already has a property called DataContext, so my inherited class will also have this property.. -
If you want to access the DataContext property in code behind, give the user control (or any controls for that matter) a name:
in code behind:
myControl.DataContext = someobject;
Although in your example setting the DataContext to "Test" will accomplish nothing.
Read up on data binding in WPF http://msdn.microsoft.com/en-us/library/aa480224.aspx
0 comments:
Post a Comment