tags:

views:

548

answers:

2

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?

A: 

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

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

eKek0
UserControl already has a property called DataContext, so my inherited class will also have this property..
Robbert Dam
+1  A: 

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

Spink