MVVM - navigating between views - silverlight

I have a ListBox that is bound to a ViewModel that exposes a parameter of type ObservableCollection. I have setup an ICommand that gets fired when one of the rows in the ListBox is selected. (using method 3 in this post - it works great by the way).
Now my question (which has nothing to do with method 3 described above or the ListBox) is when my ICommand is fired and what I want to do is navigate to a different page (eg: details page), where is the logic stored (or how do I do it?).
The reason I ask is that I am not sure how to setup the command method in the ViewModel class such that it remains testable.
ps: I am using Prism and was also wondering if it provides any classes/patterns for Navigation.

Just to elaborate on the use of IEventAggregator - it gives you a simple Pub/Sub model for sending arbitrary messages between decoupled (ie neither needs to know anything about the other) parts of the application. So we can get a reference to the IEventAggregator in our ViewModel constructor (this is automatically resolved for you by the framework) ie:
private IEventAggregator eventAggregator;
public PublisherViewModel(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
Then in our selection changed handler, we can publish the event:
var changedEvt = eventAggregator.GetEvent<MyListboxChangedEvent>();
changedEvt.Publish(selectedItemId);
This relies on our custom event class MyListboxChangedEvent:
public class MyListboxChangedEvent : CompositePresentationEvent<int> {}
So finally, in the ViewModel which responds to this action, we set up a subscription to the event, and corresponding handler method:
public SubscriberViewModel(IEventAggregator eventAggregator)
{
var changedEvt = eventAggregator.GetEvent<MyListboxChangedEvent>();
changedEvt.Subscribe(OnListBoxChanged, ThreadOption.UIThread);
}
public void OnListBoxChanged(int selectionId)
{
// do whatever we need
}
Seems like a lot of glue, but it becomes a logical method for wiring the different parts of the UI together, and it becomes second nature pretty quickly.

Have you considered using the EventAggregator to send the message that you want to show a different view. The StockTrader application included in the PRISM distribution will provide a good example of the use.

Related

Correct way to handle commands that rely on multiple view models

I'm relatively new to WPF and MVVM and i am trying to understand how to use commands correctly when they have dependencies in more than 1 view model.
A couple of examples:
In my current application i have a RelayCommand which causes a save action to occur in a couple of different view models (they write a couple of different files). Currently i am handling this using a the mvvmlight messenger to send a message to those view models to get them to do the save which i think is the correct way to do it as it avoids having to provide some kind of delegate or event to/on those view models.
I have a RelayCommand in a view model that has a CanExecute method which relies on the state of 2 other view models. I've currently handled this via the mvvmlight messenger as well by having changes in the view models the CanExecute method depends on message that their state is now valid for the operation. This seems messy but the only alternative i could think of was to use a delegate or event effectively weaving the view models together which i believe i should be avoiding.
Is there some generally accepted way to deal with this which i am missing?
In general your view model layer should have a 1:1 relationship with your view, there should be no good reason for a "Save" function to exist in a view model which is then called by another view model.
What it sounds like you should be doing is putting that logic into a service i.e. something like this:
public interface ISerializationService
{
void Save(SomeData data);
}
Then you need an implementation for this service that does the actual work:
public class SerializationService : ISerializationService
{
void Save(SomeData data)
{
// actual save happens here
}
}
Your view models should then contain properties that point to instances of these services:
public class MyViewModel : ViewModelBase
{
[Inject]
public ISerializationService SerializationService { get; set; }
// called when the user clicks a button or something
private void ButtonClickCommand()
{
this.SerializationService.Save(this.SomeData);
}
}
The only question remaining is "What sets the value of SerializationService?", and for that you need a dependency injection framework. There are plenty out there, MVVMLight installs one itself, but Ninject is the de-facto standard. When implemented properly the injection framework will create all view models for you and then "inject" the dependencies, i.e. your SerializationService property, of type ISerializationService, will be initialized with an instance of your SerializationService class (which in a case like this will also be configured to be a singleton).
Dependency Injection takes a bit of work to get your head around but once you start using it you'll never look back. It facilitates complete separation-of-concerns whilst alleviating the need to pass pointers to everything all up and down your architectural hierarchy.

How can I trigger some code to run in the view from the view model?

What is the best way for the view model to "ask" the view to do something, (e.g. manipulate on of the controls)? I don't think that the view model sending events violates MVVM as after all the INotifyPropertyChanged interface is an example of view models sending events to views.
I realize that having code behind in the view is not considered ideal from a MVVM perspective, so I could use an attached behavior to manipulate a particular control for example but the problem remains - how do I ask the attached behavior to do something from my view model?
I could have Boolean dependency property on my view with property changed event handler which runs the code I need to run. I could then bind this property to a property on my view model and then toggle the value of this property whenever I want to trigger the code to run. However this seems like a hack.
I could have an event on the view model and then explicitly attach this event to an event handler in the view in code but this seems anti MVVM - I should be able to achieve the connection using binding.
This must be a fairly common scenario, are there any standard solutions?
You could for example use an event aggregator or a messenger to send an event or message from the view model that the view handles in a loosely coupled way. Both the view and the view model know only about the event aggregator but they don't know anything about each other. Please refer to this blog post for more information about the concept.
Another common approach is to implement an interface in the view and inject the view model with this interface, e.g.:
public interface IDoSomething
{
void DoSomething();
}
public partial class Window1 : Window, IDoSomething
{
public Window1()
{
InitializeComponent();
DataContext = new ViewModel(this);
}
public void DoSomething()
{
//do something...
}
}
public class ViewModel
{
public ViewModel(IDoSomething doSomething)
{
//...
}
}
This doesn't break the MVVM pattern as the view model knows about and is dependant only on an interface.

Custom property injection in Castle Windsor for Windows Forms

I have a Windows Forms application which makes use of an MVP pattern. Each view is a WinForms user control and is backed by a presenter which handles non-UI concerns. The application makes use of Castle Windsor, and all views presenters and many other components are resolved via the Windsor Container.
What I would like to be able to do is customise property injection for the user control views. My views don't make a whole lot of use of property injection, but it is occasionally very useful and works well. The problem is, my user controls often contain nested controls, which in turn can contain other nested controls, and property injection is not going to work for these nested controls, because they were not directly resolved via the container.
What I would like to do is to configure property injection for components that inherit from the SWF Control class. In addition to finding properties on the component, I would like to also find properties on nested controls (in the Controls) collection and inject into these nested properties as well.
I know that Castle Windsor is extremely flexible and configurable so this may be possible. I need a bit of a nudge in the right direction though. Is this possible? Has anyone tried to do something similar?
If I have understood your question correctly I think that the only way to achieve what you want is by some sort of poor man's dependency injection because the way the winforms designer generates a method that constructs the various sub-controls you speak of makes it decidedly uncondusive to IoC.
I am not sure you will be able to do property injection but you can utilise the constructor, here is a hair-brained scheme I have just concocted ...
Firstly, create some way to access your windsor container - something like this would probably do the trick:
public static class MyContainer
{
private static readonly IWindsorContainer _container = Bootstrap();
// I did it like this so that there is no explicit dependency
// on Windsor - this would be the only place you need to change
// if you want an alternate container (how much you care about
// that is up to you)
public static T Resolve<T>()
{
return _container.Resolve<T>();
}
private static IWindsorContainer Bootstrap()
{
var container = new WindsorContainer();
container.Install(FromAssembly.This());
// ... whatever else you need to do here
return container;
}
}
Secondly, in the inner controls, where you want some properties injected do something like this (I went for the good ol' ILogger as an example of something you may want injected):
public partial class MyFancyControl : UserControl
{
// Constructor to keep the winforms designer happy
public MyFancyControl()
: this (MyContainer.Resolve<ILogger>())
{
// Intentionally always blank as this
// is an un-unit-testable method
}
// Constructor that does the actual work
public MyFancyControl(ILogger logger)
{
InitializeComponent();
Logger = logger;
}
public ILogger Logger { get; private set; }
}
Note: using the logger raises one of the couple of obvious smells in this - sometimes you don't register such a component with the container at all (usually you have a null logger) so you may need to hook up some sort of mechanism for that but I leave that up to you if you need it or not.

Passing Model Between Silverlight Views

Since the basic navigation mechanism in Silverlight only allows passing arguments in a querystring, when we want to pass complex data (e.g models) between our views, we use the IEventAggregator's pub\sub mechanism.
But the question is - is there a better way to pass complex information between views?
What are the cons of using the IEventAggregator for this?
This is why I switched to a ViewModel first approach. Views really aren't configurable nor should they really be passing ViewModels around. It made a lot more sense to me for a ViewModel to load another ViewModel like:
Show.Screen<OrderDetailsViewModel>(vm => vm.OrderId = orderId);
This is from the Build your own mvvm framework talk and is also similar to how Caliburn Micro works.
I can't tell you why IEventAggregator is bad, maybe it's not so intuitive? When you look at your app - you want to see what's going on and doing events with some data doesn't seem to be good. Event is event. You can share some data via Region's context in PRISM.
I'm solving same kind of issues using MEF. So, you can define something like
[Export]
public class MyModelService
{
// Code here whatever shared data you want
}
public class MyViewModel
{
// Import this shared ModelService
[Import]
public MyModelService ModelService
}
So, if you had some data in ModelService - by default MEF will compose it just once (effectively making it shared) and every time you import it inside ViewModel this instance will be there. Then you can use Events originated from ModelService to tell components when data updated, etc.
I'm currently using a Session idea, like in ASP.NET. I've defined a static object named SilverlightSession and add a Values property of type Dictionary. Then I just add to the values dictionary or update it and cast it
public static class SilverlightSession
{
public static Dictionary<string, object> Values { get; private set; }
}
in the app.xaml.cs startup:
SilverlightSession.Values = new Dictionary<string, object>();
Then you can have your models in "session" until the application closes.

How to open a new window using MVVM Light Toolkit

I am using MVVM Light toolkit in my WPF application. I would like to know what is the best approach for opening a new window from an existing window. I have got this MainViewModel, which is responsible for MainWindow of my application. Now in the MainView, on a button click, I would like to open a second window on top of it. I have got RelayCommmand binded to the Button's Command. In the RelayCommand's method, I can create a new window object and simply call Show(), something like this:
var view2 = new view2()
view2.Show()
but I don't think the ViewModel should be responsible for creating the new view2 object. I have read this post WPF MVVM Get Parent from VIEW MODEL where Bugnion has suggested to pass message to the view1 from the viewmodel1 and then view1 should create the new view2. But I am not sure what does he actually mean by passing the message to the view1? How should the view1 handle the message? In it's code behind or what?
Regards,
Nabeel
Passing a message from ViewModel1 to View1 means to use the messaging capabilities in the MVVM Light Toolkit.
For example, your ViewModel1 could have a command called ShowView2Command, then it would send a message to display the view.
public class ViewModel1 : ViewModelBase
{
public RelayCommand ShowView2Command { private set; get; }
public ViewModel1() : base()
{
ShowView2Command = new RelayCommand(ShowView2CommandExecute);
}
public void ShowView2CommandExecute()
{
Messenger.Default.Send(new NotificationMessage("ShowView2"));
}
}
View1 would register to receive messages in its code behind and display View2 when it receives the correct message.
public partial class View1 : UserControl
{
public View1()
{
InitializeComponent();
Messenger.Default.Register<NotificationMessage>(this, NotificationMessageReceived);
}
private void NotificationMessageReceived(NotificationMessage msg)
{
if (msg.Notification == "ShowView2")
{
var view2 = new view2();
view2.Show();
}
}
}
Why do you go this route? Its simple. If you replace your button with a toggleButton, or a hyperlink, or any other number of button-like controls, you don't need to update your "code behind" - its a basic principle of the MVVM pattern. In your new toggleButton (or whatever), you still end up binding to the same exact Command.
For example, I'm creating a project for a client who wants to have 2 UI's - one is going to be fundamentally different in every way, in terms of presentation. Horizontal tabs vs Vertical RadPanelBar (think Accordion) for navigation. Both of these views can point to the same viewModel - when a user clicks the Work Order tab in View 1, it fires the same "WorkOrderCommand" that's fired in the Work Order Header in the panel bar.
In a code-behind model, you'd have to code two separate events. Here you only have to code one.
Furthermore, it allows a designer using Blend to create any layout they want. As long as they have the hooks (EventToCommand control) in place, myself (as a developer) couldn't care less what the final product looks like.
Loose coupling is incredibly powerful.
You can do in this way like you need to create some events and register those in view and call these in view model.and open that pop up window.
Like This example
public class Mainclass : MainView
{
public delegate abc RegisterPopUp(abc A);
public RegisterPopUp POpUpEvent ;
public RelayCommand ShowCommand { private set; get; }
public void ShowCommand()
{
ShowCommand("Your parameter");
}
}
inside the view MainView mn=new MainView();
Register the event here like thake mn.POpUpEvent += than click on tab button double time
and in registers popup method right the code for opening the pop up window.
Unless I am missing the point here - if I were to use the code behind, then why not directly implement button_click event and open the second view?
What Bugnion seems to be suggesting is view1 -> button click -> relay command -> viewmodel1 -> message -> view1 -> view1.cs -> open view 2.
You are going to sacrifice testability anyhow by writing code-behind, so why take such a long route?
You can abstract the view specific features into services using generic interface. In the view layer you can provide concrete instances of these services and build view models using the IoC container and Dependency Injection technique.
In your case you can build an interface IWindowManager or something similar which has the required method. This can be implmented in your view layer. I wrote a small blog post recently demonstrating how to abstract the dialog behaviour out of view model. Similar apporach can be used for any user interface related service like Navigation, MessageBoxes etc.
This link might be helpful for you http://nileshgule.blogspot.com/2011/05/silverlight-use-dialogservice-to.html
Many people also use the approach of firing events from view models which are subscribed on the view.cs file and from there the MessageBox or any other UI related action is performed. I personally like the approach of injecting services because then you can provide multiple implementations of the same service. A simple example would be how navigation is handled in Silverlight and Windows Phone 7 applications. You can use the same view model but inject different implementations of the Navigation service based on the application type.
I find the best way to approach this, is opening and closing the window from the ViewModel. As this link suggests,
Create a DialogCloser class
public static class DialogCloser
{
public static readonly DependencyProperty DialogResultProperty = DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(DialogCloser), new PropertyMetadata(DialogResultChanged));
private static void DialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = d as Window;
if (window != null) window.Close();
}
public static void SetDialogResult(Window target, bool? value)
{
target.SetValue(DialogResultProperty, value);
}
}
Create a Base ViewModel inheriting from GalaSoft.MvvmLight.ViewModelBase with there additional members. Once done, use this viewmodel as base for other viewmodels.
bool? _closeWindowFlag;
public bool? CloseWindowFlag
{
get { return _closeWindowFlag; }
set
{
_closeWindowFlag = value;
RaisePropertyChanged("CloseWindowFlag");
}
}
public virtual void CloseWindow(bool? result = true)
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
CloseWindowFlag = CloseWindowFlag == null ? true : !CloseWindowFlag;
}));
}
In the view, Bind the DialogCloser.DialogResult dependency property with the CloseWindowFlag property in the base viewmodel.
Then you can open/close/hide the window from the viewmodel.

Resources