Design pattern for Viewmodel change triggering another viewmodel change? - wpf

In my WPF application, I have several models and viewmodels. Consider an example:
The SurfaceCondition property of my RoadViewmodel changes. I want this to (asynchronously) trigger a change of the Wheel property of my CarViewmodel.
I can think of several solutions, but I sense this particular problem has a well-recognized solution. Using messages? Putting a reference in the RoadViewmodel to the CarViewmodel and trigger an update through the property? Merging the viewmodels? WPF gurus out there, please enlighten me!

Definitely not the two last solutions you propose as they violate Seperation Of Concerns (RoadViewModel knowing about CarViewModel) / DRY principles (RoadViewModel having to update CarViewModel or merging two classes).
Messages on the other hand seems like a fine, decoupled solution here. There are a couple of implementations available, for example Prism has en EventAggregator class, MVVM Toolkit has MessageBus etc. Or search for terms like 'MVVM event bus'. Now whatever you choose, know that it is always good to not use those classes directly but instead pass an interface. For example with Prism, you'd program your viewmodels to use the IEventAggregator interface only. In the actual application you pass them an instance of the actual EventAggregator, whereas during unit tests you pass the a mock.

Related

How to use MediaElement.NaturalDuration to set MediaTimeline.Duration in WPF MVVM

My MVVM program is a media player and uses the Media Element's Natural Duration property to set the Media Timeline's duration. Before I implemented MVVM design pattern, I could simply put
MyMediaTimeline.Duration = MyMediaElement.NaturalDuration;
in the code-behind. I am new to using MVVM but I believe this is not the correct way to perform this action according to the MVVM design pattern. I believe that MediaElement.NaturalDuration is not a dependency property so it cannot be bound to directly. Do I need to make it a dependency property somehow? Would this be coded in the ViewModel?
When we need to implement functionality like this that relates to UI controls using MVVM, we have a few options. One is to implement some kind of service or manager class that can implement this functionality for us and another is to use Attached Properties. Out of these two options, I believe this second option to be more suitable for this problem.
However, there is absolutely nothing wrong with adding event handlers into the code behind of your view, even when using MVVM. I keep seeing new users panicking over what to do rather than use the code behind when using MVVM. This is a common misconception about MVVM.
If you really know how to use Attached Properties properly, then I would advise that you use one (or more) of those to solve your problem, otherwise I would happily advise you to use the code behind. Note that if your view models are correctly data bound to your views, then you can access your view model from the code behind like this:
TypeOfViewModel viewModel = (TypeOfViewModel)DataContext;

Silverlight - communicate between viewmodels

This UI consists of a Main.xaml which contains a navigation frame which holds (Person.xaml), so there's two different viewmodels involved.
I would like to filter the content of the datagrid when the menu in Main.xaml is clicked.
People (shows all)
Score above 50
Score below 50
My approach is to use the MVVM light Messaging by having PersonViewModel subscribe on a certain message which is sent from MainViewModel. This would work, but are there any other ways of doing this (best practice)?
I'd hate to implement the MvvmLight Messaging for all my scenarios where UI elements from different viewmodels have a need to communicate, if there is a better way of solving this.
If you are using MVVM light, I guess you have created these viewmodels in the ViewModelLocator. So just use it to get access among viewmodels in your application.
Another approach is to use some type of IoC container like Unity or SimpleIoC.
I hope this helps you.
We use MVVM light also. From my understanding of your requirements. you can probably just use a single DomainContext and then loading all the entities to it and then querying the context for each click item.
once you have a Context, you can basically query it dynamically. Here's something from one of my code.
GetUserBUGroups = SecurityDomainContext.Current.UserBUGroups.Where(ub => ub.UserID == GetUsers.UserID).OrderBy(o => o.BUGroup.BUGroupDesc).ToList();
For simple scenarios such as this, it does not seem appropriate to use several ViewModels.
I believe you should insert the filter options directly in the PersonViewModel

Choosing between bound ViewModel properties or messaging to communicate between ViewModel and View using the MVVM Light Toolkit

I'm using MVVM Light toolkit (which I love). I currently have messaging in place for some interaction originating from the ViewModel and intended for consumption by the View. Typically these types of messages indicate the View should do something like hide itself, show a confirmation message that data was saved, etc.
This works. In the constructor for the View, I register with the Messenger:
Messenger.Default.Register<NotificationMessage<PaperNotification>>(this, n => HandlePaperNotification(n));
When I'm using the Messenger to communicate cross-cutting concerns between ViewModels (like identity), I can see that when the ViewModel is cleaned up in the ViewModelLocator, the base class for ViewModels (ViewModelBase) unregisters any subscribed messages. I don't have to do anything, as MVVM Light Toolkit handles that for me. However, when I use them in the Views, I have to expressly unregister them at Closing time, like so:
Messenger.Default.Unregister(this);
I suppose I could implement a base class for Views to inherit from.
However, it strikes me that perhaps this is a code smell to be using the Messenger in the View... it works, but it might not be the best way. I'm wondering if I should instead create a property on the ViewModel and bind whatever part of the View's elements to it. In the example of hiding a form, a property could be a boolean called "Show". As I think about it, I can see that in many cases this will result in having to write a ValueConverter. One way seems less testable. The other way seems to require much more code and perhaps the introduction of excess ValueConverters, which could become a code smell in themselves.
So (after all that build up) my question is this:
Is it preferable to use messages within the View or is it better to add properties (and potentially ValueConverters) to allow the ViewModel to drive it in a more bindable fashion?
In MVVM. ViewModel comunicates with View through DataBinding and Commands. If you need some other functionality, you need to implement it using this means.
Messaging is supposed to be only for ViewModels. Views are supposed to be "stupid" visualisers of your data in ViewModel.
The Messaging logic in MVVM Light is there for communication between ViewModels. I've never run into any communication between View and ViewModel that I couldn't solve with binding and/or commands. Sometimes I need Value Converters and sometimes I need code in the code-behind, but I've never had to make the ViewModel directly push data to the View.
This is an interesting discussion and I found this thread when I was wondering about view model to view communication. Interestingly, MVVMLight's creator seems to find it perfectly acceptable to send messages from a view model to a view. Another example of differing opinions about what is a good MVVM design.

wpf mvvm confusion

as per my understanding about mvvm is.
there is a model (entity class that also implement inotify...), view (xaml code) and some class as vm (kind of controller which normally inherit icommand) to let us make events/commands to be generated on specific event...
m just wondering about difference between viewmodel class and xaml's code behind class... why don't we simply consider and enhance code behind...
no considerable reason is in my mind to justify this...
or kindly write somethng with example to clear mvvm... and why mvc or mvp is hell for wpf app????
The Model does not implement INotifyPropertyChanged, the ViewModel does. The actual WPF view data-binds to the ViewModel. There is now a lot of documentation online for this.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
MVVM is identical to Fowler's
Presentation Model, in that both
patterns feature an abstraction of a
View, which contains a View's state
and behavior.
http://blogs.msdn.com/johngossman/archive/2005/10/08/478683.aspx
In practice however, only a small
subset of application UI can be data
bound directly to the Model,
especially if the Model is a
pre-existing class or data schema over
which the application developer has no
control. The Model is very likely to
have a data types that cannot be
mapped directly to controls. The UI
may want to perform complex operations
that must be implemented in code which
doesn't make sense in our strict
definition of the View but are too
specific to be included in the Model
(or didn't come with the pre-existing
model). Finally we need a place to
put view state such as selection or
modes. The ViewModel is responsible
for these tasks. The term means
"Model of a View", and can be thought
of as abstraction of the view, but it
also provides a specialization of the
Model that the View can use for
data-binding. In this latter role the
ViewModel contains data-transformers
that convert Model types into View
types, and it contains Commands the
View can use to interact with the
Model.
MVVM is associated with WPF because WPF's data binding mechanism when combined with this pattern makes testable GUIs a breeze.
Check this two videos to get some idea. Both videos show developing application starting with everything in code behind and then they refactor to MVVM pattern.
Mike Taulty's series of videos (in fact there is 10 videos in total, check at least first and second)
Jason Dolinger on Model-View-ViewModel
Also, see this SO question for more links: MVVM: Tutorial from start to finish?
why don't we simply consider and enhance code behind...
(In addition to what other have already mentioned:) because it make your code easier to read. In the code behind file, you have UI stuff that is impossible or to complicated to do in XAML. In the view model code file, you have everything related to filling your form with data.
As with all design patterns, blindly following it is not the best idea. For very small windows, MVVM might not make sense. For larger windows, MVVM forces you to make a separation of concerns, which will usually make both your code behind file and your MVVM class easier to read, to understand and to debug.
First, for MVVM purposes you don't need the VM to inherit ICommand. Instead, VM contains a set of properties of type inherited from ICommand. So that View just binds to those properties. F.i.:
<Button Command="{Binding DoSomethingCommand}" />
And code-behind isn't used because it's basically inseparable part of the View. It's the same class your View is. You can't easily test it, and your code is often tightly coupled to the XAML.
And Model is not really obliged to (but can) support INotifyPropertyChanged. Whereas ViewModel should of course implement this interface to allow binding.
I suggest you to read a few introducing articles on the subject. It's not that confusing. This can be the first one: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
why don't we simply consider and enhance code behind...
Code behind is often (always?) the simplest approach...if you're a developer. But MVVM is designed to assist more than just a developer. MVVM is for the database girl and the graphics guy too.
Separating M (for the db) and V (for the artist) and VM (for you) allows each person to work independently of each other. So, for example, you don't have to wait for the graphics guy to make a UI before you can wire up the db. You can all work in parallel (in theory).
Separation of concerns means separate jobs.

Need advice on implementing UI in WPF

I need some advice on implementing UIs in WPF.
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
I've looked at MVP (and its WPF variant - MVVM), but having some trouble getting started.
Assuming I have a UI to build, here's what I think I should do:
1.
Create a "Main UI" Mediator class which specifies ALL high-level operations (LoadSettings(), SetVisibility() ) and events (not triggered by the user, e.g, model data changed) that my UI supports.
2.
Create the "Model" classes to represent the data
3.
Create "ViewModel" classes for my model classes.
4.
For complex behaviours (e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection), do not rely on ViewModels to update the UI. Instead, do it manually through the Main UI Mediator class.
5.
For simple behaviours (e.g, toggling the visibility/enabled states/etc), use WPF binding to bind the ViewModels' properties directly to the UI.
In this case, the Main UI Mediator class would maintain both the ViewModel and Model objects, and delegate user interactions (to the Model) and UI update requests (to the ViewModel/View) appropriately. The Mediator class also provides a centralised interface which specifies the functionalities of the UI, while acting as a Change Manager (described in GOF's Observer Pattern) to handle complex UI behaviour/reduce redundant UI updates.
Am I on the right track? Should I tweak my approach? Change it completely? At the moment, I lack the experience/knowledge to implement huge/complex UIs, so I don't really know whether I'm on the right track.
Thanks
This is a bit long, sorry about that!
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
Yep :) Anytime you have to name a control and write "someControl dot blah" in your code-behind, that's a code smell. It's sometimes unavoidable, but try to limit it as much as possible. Your UI is a projection of the model - ViewModels and ValueConverters are a way to deal with the impedance mismatch between the two domains.
A few problems with your approach:
Create a "Main UI" Mediator class which specifies ALL high-level operations
Instead of doing this, your Window class acts as the "Controller"; the important thing is, use Commanding to define your top-level actions. This way, you can have UserControls decoupled from the Window class, because the UserControl will just call Commands.Open.Execute(null, this), and the Window can handle it, and the UserControl will never explicitly have a dependency on the Window.
Create "ViewModel" classes for my model classes.
In MVVM, the VM part is to help you out - if you can get away with binding directly to the model (i.e. the data doesn't change or you don't mind implementing INotifyPropertyChanged in your models), then doing this (even if you have to use a few IValueConverter classes) is okay. ViewModels are mostly used when the view is so different from the model representation that it'd be ugly to hack up your model, or to "tack on" extra properties that only make sense in this particular view.
while acting as a Change Manager...
Remember that WPF does this for you, via Dependency Properties and INotifyPropertyChanged; don't reinvent the wheel; if you write an OnDataUpdate() function, this is a sign you're not using data binding properly.
e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection
This is where Commanding is great - your CanExecute function can apply arbitrarily complex logic to decide whether a certain operation can be done, and if you bind it to UI elements like Menus or Buttons, they will automatically disable/enable as needed.
It hasn't been mentioned, but do all of your UI design in XAML.
There is nothing worse than seeing WPF UI's being created via code-behind.

Resources