Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's wrong with "DataContext = this" in WPF user controls?

I read somewhere that setting DataContext = this in the constructor of a user control is bad practice (can't find where though). Why is this bad practice? What is the alternative?

like image 568
Deniz Dogan Avatar asked Jan 28 '10 10:01

Deniz Dogan


People also ask

What is the use of DataContext in WPF?

Every FrameworkElement can be associated with a DataContext which will be used as the default data source during binding, if no other data source is specified in the binding code. Also, the children of this FrameworkElement auotmatically inherit this setting.

What is UserControl DataContext?

DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControl s unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel .

What is DataContext?

The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.


1 Answers

In general, when someone uses your control they are going to want to set it's data context to their own view model class and bind the properties on your control to their view model.

If you start messing around with the data context internally within the control, and rely on it being set to 'this', either you will prevent their binding from working, or your control won't work as expected because you rely on it not being changed.


Say you have a user control that has a bunch on sub controls on it. What you could do instead is set the DataContext on the sub controls to be your user control class (or whatever you wanted). This would allow you to bind those sub controls to your user control's properties, while still allowing any users of your control to set it's data context to their view model and bind to the properties as well.

like image 161
Simon P Stevens Avatar answered Oct 21 '22 12:10

Simon P Stevens