Know when the "Datacontext" is Changed in the Code Behind the UserControl

I am creating a usercontrol for lightwitch. This is basically the Silverlight user control that gets the business object in the DataContext property.

I can bind in xaml elements without problems, but behind the code I don’t know how to get the information when the dataContext has changed?

I need this for one special binding.

Many thanks!

+6
source share
2 answers

You can extend the management class ( UserControl in your case) and add a new DependencyProperty DataContext package to open the PropertyChanged . See these three posts and this question . Alternatively, it may happen that you do not need to listen to DataContextChanged , depending on what you are trying to do, as it may be more appropriate to handle the changes in your model.

Finally, if you have the patience and the option, I hear that SL 5 provides a DataContextChanged .

+6
source

I am afraid that you cannot set the readonly static field again unless you do this with the β€œnew” one.

You might be able to catch a DataContext modified by binding data to a DataContext dependency dependency. for example Register a new dp named "MyDataContext" and create a binding.
The DataContext is the binding source, and MyDataContext is the target binding, i.e. DataContext ---> MyDataContext. So every time you get a DataContext MyDataContext dp, change the callback. I think this will work, but not tested.

The code is as follows:

 // dp declaration.. public static readonly DependencyProperty MyDataContextProperty = DependencyProperty.Register(null, "MyDataContext", typeof(object), typeof(MyControl), new PropertyMetadata(MyDataContextChangedCallback)); // create binding in constructor or initialization. Binding binding = new Binding("DataContext"); BindingOperations.SetBinding(this, MyDataContextProperty, binding); 

thanks

+2
source

Source: https://habr.com/ru/post/902652/


All Articles