Reputation: 4107
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?
Upvotes: 4
Views: 10385
Reputation: 111
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
Upvotes: 3