I have a multi-part question:
(1) Is there a good reason why Silverlight doesn't expose a DataContextChanged event? It seems like a whole lot of hassle could be avoided if someone at Microsoft just changed internal
to public
in the FrameworkElement class (like WPF does).
(2) I've found one or two different methods for hacking your way into a DataContextChanged event by using DependencyProperties in one configuration or another. But I can't get them to work reliably. My testing so far seems to show that they fire the hacked DataContextChanged event just fine for the first class to which I hook them up, but don't fire for any other classes. Has anybody else run into that problem? Or better yet, have they worked their way around it?
(3) The reason I've been giving myself for wanting to know when my DataContext has changed is that there are some UI operations that are complicated to get right in XAML, but are trivial in code-behind; and for many of those things, I need to handle events raised by my ViewModel; and hence I need to know when my ViewModel has changed, so I can wire up the event handlers. Is this an accurate view of the world? Or is the fact that I'm wanting to deal with this sort of thing in code-behind a pretty good indication that my thinking has gone off the rails some ways back? I'm no MVVM purist: I just want to get from here to good code quickly, and I don't particularly care how I get there. Code-behind has served me reasonably well for over a decade now, and I'm loth to abandon it entirely. But is my pragmatism making it harder on myself at this point?
"But is my pragmatism making it harder on myself at this point?"
I wouldn't call it pragmatism. I'd call it fear of change; staying in your comfort zone. Life is actually far easier if you abandon your old way of thinking and embrace the new (and I know exactly what you mean - I was in the same boat as you with code-behind).
Now, off my soap box and to a more practical answer:
When you want to detect changes in your model, then hook into the events that allow you to detect changes in your model. The DataContext is not really the model... All of your model objects are going to have an implementation of INotifyPropertyChanged. You should either be hooking into that for a given model, or hooking into something similar for an ObservableCollection.
Silverlight/WPF make all of this sort of stuff WAY easier now that databinding actually works.
Don't fight the framework. Don't bring old ASP.Net practices with you to this game... It will not help you. You'll lose the best parts of the framework's power that way.
Cheers.
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