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?
问题:
回答1:
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.