I spent a bit of time last week wondering why I was having issues with my bindings. Hopefully this will help someone who finds the same issue…
Here’s a simple example of the problem I was having: I had a data grid showing a summary of the customers, it could be expanded to see the detail of the customer. My detail view was a user control already written which required it’s data context set correctly; it assumed it was bound to the CustomerDetail object, not the CustomerSummary.
Here’s the XAML I wrote:
Imagine the Grid inside the DataTemplate of the RowDetailsTemplate is my CustomerDetail user control. As you can see I’ve set the DataContext to the Detail. But when I expand it I get a binding error:
After some investigation I found that the grid propagates the data context to the root element in the data template by setting it to the data context of the row you’ve expanded. However, if you’ve already set a data context it will not propagate it. So changing the RowDetailsTemplate to this, it works:
The superfluous Grid has no data context, so it is automatically propagated. I can put my user control in that grid and set the data context as I required. I’m pretty sure this is a bug but it’s easy enough to work around. Once you figure out what’s going on!