4

TestScenario:

I've got a Control with a DependencyProperty A. I've got a ViewModel with a property A that I bind against the Control's A-Property using the OneWayToSource Binding. The Binding is updated explicitly by the Control.

I switch out the bound ViewModel instance at runtime, thereby changing the underlying Source of my Binding. When this happens I would like an Event to fire that tells my control that I can now update the value of its DependencyProperty A. The reason is, that as soon as you change the bound ViewModel, the DependencyProperty A's DefaultValue is written to the Source. Instead, I would like the control to come up with a proper value and update the source manually.

One might think that just listening to the DataContextChanged event solves the problem. However, when this Event gets fired, the Source of the BindingExpression still points to the old ViewModel.

The only hackaround I can come up with, is to use Dispatcher.BeginInvoke with the DispatcherPriority.DataBind priority in the EventHandler of DataContextChanged.

It works, but does not feel clean to me.

I am looking for an event in the Binding-class that notifies me about changes of the Source... however I cannot find one.

Thank you

TwinHabit
  • 753
  • 8
  • 22
  • Have the same problem… and came up with the same workaround, i.e. BeginInvoking in the `DataContextChanged` handler and setting the DP value again and explicitely updating the source. Unfortunately this only works when the binding’s source is really the element’s data context, but not when using a relative source to something else… :/ – poke Jul 11 '13 at 13:03

1 Answers1

0

Perhaps I'm not understanding the question completely, but can you just use the NotifyOnSourceUpdated or NotifyOnTargetUpdated properties (and the corresponding SourceUpdated or TargetUpdated events)?

Brian S
  • 5,675
  • 1
  • 22
  • 22
  • Unfortunately not. Those events only fire when a Property on the Source (NotifyOnSourceUpdated) or on the Target (NotifyOnTargetUpdated) gets updated due to the binding. However, I switch out the DataContext itself, so I don't update the Source but I rather swap it out completely. Makes sense? :) – TwinHabit Aug 09 '12 at 20:08
  • Perhaps you can post some code that demonstrates the issue. It sounds like you need to know when the DataContext has Changed, but _after_ the Binding has been updated? Is it a matter of [forcing the binding to refresh](http://stackoverflow.com/questions/656552/is-it-possible-to-refresh-wpf-data-bindings) from the DataContextChanged event? – Brian S Aug 09 '12 at 20:20
  • It's not a matter of forcing the binding to refresh. The binding refreshes just fine, but I need to react as soon as the datasource has changed so that the control can Update its property's value, thereby updating the value in the view model. Maybe the Dispatcher.BeginInvoke really is the way to go here... – TwinHabit Aug 09 '12 at 23:56