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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With