简体   繁体   中英

Know when the “Datacontext” is changed in the code behind of a UserControl

I'm creating a usercontrol for lightswitch. This is basically a Silverlight usercontrol, which receive the businessObject on the "DataContext" property.

I can bind in the xaml side items without a problem, but on the code behind, I don't know how to get informed when the dataContext has changed?

I need that for one special binding.

Thank you very much!

You can extend the control class ( UserControl in your case) and add a new DependencyProperty wrapping DataContext in order to expose PropertyChanged . See these three posts and this question . Alternatively, it may be the case that you don't really need to listen to DataContextChanged , depending on what you're trying to do, since it might be more appropriate to handle the changes in your model.

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

I'm afraid you cannot set the static readonly field again unless you do it with a "new".

You might be able to catch the DataContext changed via a data binding to the DataContext dependencyproperty. eg Register a new dp named "MyDataContext", and create a Binding.
DataContext is the binding source and MyDataContext is the binding target, that is DataContext ---> MyDataContext. So everytime the DataContext you gonna get your MyDataContext dp changed callback. I think this gonna work but not tested.

the code is like:

// 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM