Question

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?

Was it helpful?

Solution

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

OTHER TIPS

You need some field or propertie in MyUserControl's class named DataContext.

See here to learn about user control properties in .net.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top