Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 607
J4N Avatar asked Nov 29 '11 14:11

J4N


2 Answers

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.

like image 68
Esoteric Screen Name Avatar answered Oct 12 '22 11:10

Esoteric Screen Name


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. e.g. 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

like image 45
terry Avatar answered Oct 12 '22 12:10

terry