How to implement print operation using MVVM - wpf

In my view-model i have an command which implements print operation using PrintVisual of PrintDialog class . As i don't have the access to the view i cannot print it .how should tackle this ?
Is there an easier and better approach?

I think your solution would be to pass a service class in that performs the work of printing the grid, showing a dialog, and whatever work is required to get the job done.
In MVVM, most of people use dependency injection to do this. You would create another service with the same interface for your tests to use that wouldn't block execution. The service, in this case, is a view layer service, and should have no dependency back to the viewmodel. The only thing the viewmodel knows is that it has a service interface to call into, and the only thing the service knows about the viewmodel is the interface it implements for this interaction.
I read this Wikipedia article that has helped me in the past:
SOLID - Wikipedia
Let me know if this makes sense.

This is how i solved it.
I created an event in my viewmodel. Raised the event here whenever i want to print operation.
I defined my listener method in the mainwindow.xaml (this is where i have defined my content presenter , and all the data templates are being assigned to this contentpresenter.content)
In this listener method i am calling the print operation using PrintVisual of PrintDialog Class.
!

Related

WPF - How to run a method of a custom control from a view model?

I work on a custom WPF Diagram Control. The control has a method that arranges the elements in the Diagram and I need to add MVVM support to call this method from my View Model.
At the moment I am a bit confused how to implement this and I hope that someome can point me to the right direction.
Maybe you need to rethink your concept. What needs to be re-aranged?
Think of ViewModel the logic behind a view and the view should be as dump as possible without any logic.
I assume also that the "arranges" method should be well tested and this could also be "easier" done on a ViewModel (if done right). Your best bet would be to place all logic in the ViewModel.
From the top of my head I could think of a DiagramViewModel with an ObservableCollection<ShapeViewModel>. ShapeViewModel can either be a base class or a concrete class which could also have some information about the location of the shape etc. The communication between the view models can be done via a Messenger (MVVM Light Messenger) or EventAggregator https://msdn.microsoft.com/en-us/library/ff921122.aspx.
If you still want to leave your architecture as you have it and want to execute a method on the view I would abstract it in a service. IDiagramUpdateService.
Look at following article which gives you good insights in communication between views and view models (and vice versa).
https://msdn.microsoft.com/en-us/magazine/jj694937.aspx
You'll find great information for both approaches.
HTH
Thanks for the quick response to my question.
I think my concept was a bit wrong, since the ViewModel should have no reference to the View.
What I would like to achieve is that I can place a button in the Main Window that calls the Arrange Method in the Custom Control.
I realized this by adding a RoutedCommand to my Custom Control.
And the Command Property of the button on the main window is bound to this RoutedCommand.
So the ViewModel is no longer involved in calling this method. It just manages the items that are shown in the Custom Control.

Call a method in app.xaml.cs from ViewModel

I have some common code written in three ViewModels, which should be refactored. I have moved the code in a method in app.xaml.cs. Is this a right approach ? Now I have to call this method from the ViewModels, should I raise a custom event (from all ViewModels) and handle it on the app.xaml.cs ? If yes that would mean I have to create references of the ViewModels on the app.xaml.cs page (we are using Unity).
Does this seem right ? I am new to MVVM, any other suggestions ?
Any help will be appreciated.
You haven't mentioned what the code is. Why is it in the App.xaml.cs file?
The fact that you need to call it from three different ViewModels would indicate that you should refactor it into either:
a static helper type class
a base class that your ViewModelss inherit from
The ViewModel's job is to hold and shape (or transform) data ready for display, but it shouldn't know about the display. Nor should it know about the contents of the App.xaml.cs, especially as your ViewModels may end up being in a totally different module or assembly to the App.xaml file.
Any time you have "Cross cutting" challenges like where 2 totally separate objects need to communicate, an event style (publisher/subscriber) pattern works well.
If you are using Unity, then use the EventAggregator.
That way you can simply publish an event from your VM and have your app.xaml.cs listen for the event.
this way you wont have to let your VM know about app.xaml.cs.

Using MVVM in WPF, should I launch child windows from View code behind, or ViewModel?

I've been puzzled by this for a while. I am writing quite a large RibbonWindow WPF application using the MVVM pattern. The screen has a RibbonBar menu along the top and the rest of it displays the various Views. Some Views contain other Views and some of these have buttons that launch child Windows.
So far, I have been doing this from the View code behind file, but I'm aware that these files are supposed to be empty when using MVVM. I could move the child window launch code to the ViewModel, but then I would need a reference to the main RibbonWindow (to set as the child window owner) and that doesn't seem right.
Any advice or tips on how this is normally achieved using MVVM would be greatly appreciated.
I usually handle this by creating some sort of WindowViewLoaderService. When your program initializes you register your Window's and your ViewModels with code something like this:
WindowViewLoaderService.Register(TypeOf(MainWindowView), TypeOf(MainWindowViewModel));
WindowViewLoaderService.Register(TypeOf(MyWindowView), TypeOf(MyWindowViewModel));
Then when you can for example call into this service from your ViewModel and all you have to reference is your other ViewModel. For example if you are in your MainWindowViewModel you might have code like this:
var myChildWindowVM = new MyWindowViewModel();
WindowViewLoaderService.ShowWindow(myChildWindowVM);
The WindowViewLoaderService would then look up what View is associated with the specified ViewModel you passed it. It will create that View, Set its DataContext to the ViewModel you passed in, and then display the View.
This way your ViewModels never know about any Views.
You can roll your own one of these services pretty easily. All it needs to do is keep a Dictionary with the key being your ViewModelType and the value being your ViewType. The Register method adds to your dictionary and the ShowWindow method looks up the correct view based on the ViewModel passed in, creates the view, sets the DataContext, and then calls Show on it.
Most MVVM Frameworks provide something like this for you out of the box. For example Caliburn has a slick one that just uses naming convention its called ViewLocator in this Framework. Here is a link that summarizes: http://devlicio.us/blogs/rob_eisenberg/archive/2010/07/04/mvvm-study-segue-introducing-caliburn-micro.aspx
Cinch on the other hand calls it a WPFUIVisualizerService which you can see in action here:
http://www.codeproject.com/KB/WPF/CinchIII.aspx
These should help get you rolling.
Well, one remark to start with is that, "Having no code AT ALL in the code-behind" is actually a "myth". If you want to be pragmatic, and you see that having some code (as little as possible would be better), will make your life easier and solve your problem, then you should go with that.
However, in this situation, there are actually some loosely coupled ways to do this. You could have a service that does the interaction for you. You initiate the interaction with the user from the ViewModel, the service takes care of that (by showing a ChildWindow for example), and gives you back the user's reponse. That service can be mocked for testing easily. And it can be tested seperately.
That is, if you want to do things yourself. If you want a framework to do the heavy lifting for you, you can check out the InteractionRequest functionaity offered by Prism. Here's the MSDN article that talks about adanced MVVM scenarios which includes a section on User Interaction Patterns. That's the way I do it, and it's pretty simple, elegant and straightforward.
Hope this helps :)
To take Matt's answer one step further, you can have all your view's be a user control. Then create a ViewContainer, which is a window with your data templates (as you described).
Then you just ship the viewmodel you wish to open over to the window service, which sets the DataContext. The service would then open the window and the contentcontrol will resolve the correct view for the viewmodel.
This means all the registration is done in the XAML and the window service just knows how to do just that...open and close windows.
This is an old post, but maybe this'll help someone along the way: I use MVVM, and raise events for opening child windows from the ViewModel back to the View. The only code behind is handling the event, opening the window, setting owner of the child window and that's pretty much it. In the viewmodel, if the eventhandler is null, then it's not subscribed to by the view and doesn't fire. The VM does not know about the view. The code is pretty simple also and only takes a few lines.
In this situation View should handle the opening of the child windows.
However, ViewModel might drive the creation of the windows, but calling into View to create a new Windows.
This will save the logic of MVVM pattern: ViewModel has the "brains" but is not involved in a particular window creation.
ViewModel only is used to present system state and UI logic. One viewmodel may be referenced by multiple views. It have no knowledge of UI specific code like parent/child relationship, position, layout, size etc. So it is better to pop child window in view's code-behind with ViewModel's state changed event or command event and event arguments. In this way you can specify which one is the parent view in the UI layer.

WPF/MVVM - how to execute commands on start-up?

I'm writing a WPF app following MVVM principles.
I wan't to execute a command on startup - I'm in doubt as to what is the best method?
The ViewModel should be indifferent as to whether there are any views, right?
Is it then 'ok' to do stuff as the last thing in VM constructor? Or is there an event for 'application is now up and running, all initialization has completed' that I can hook onto?
It feels wrong to wire it into the view model?
To be a bit concrete, I'd like to do as Visual Studio and load 'most recent solution' if the user has selected that in preferences. If the user manually loads a solution through GUI I start the flow in a MainFormViewModel and I could handle the load in last lines of constructor there?
Any thoughts?
Anders, Denmark
The Windows.Interactivity approach or asynchronously loading their preferences from the constructor are equally viable - an alternative exists if your using the MefedMVVM framework.
You can also import the IContainerStatus to attach to the view being loaded entirely from the view model (and therefore nothing to forget doing in the XAML) More info is available here
I really wanted to avoid calling methods from within the ViewModel constructor - and in my view activating events from constructor is doing just that (or at least when using Prism as I am (should have mentioned that).
I ended up doing the simple thing and simply calling a Loaded method on my main ViewModel after construction has ended.
Nonetheless, Scott singled out as the answerer - thank you all for taking the time. I appreciate your point of view even if I chose another way in the end.
Anders, Denmark
var mainViewProvider = ObjectFactory.GetInstance<IMainViewProvider>();
var mainWindowViewModelProvider = ObjectFactory.GetInstance<IMainWindowViewModelProvider>();
var mainWindow = mainViewProvider.GetView();
var mainWindowViewModel = mainWindowViewModelProvider.GetViewModel();
mainWindow.DataContext = mainWindowViewModel;
mainWindowViewModel.Loaded(Settings.Default.LoadLatestOnStart);
mainWindow.Show();
What you can do is use your MainForm's (the one which needs to load the solution) Loaded event.
Use Windows.Interactivity EventTrigger to attach a command to Loaded event. And on that command's execution, load the solution.
I would introduce Controllers which are responsible for the UI workflow. They know when the application has started and they can execute Commands. This doesn't violate with the MVVM pattern. If you are interested how this work then you might find the sample applications of the WPF Application Framework (WAF) interesting.
That's ok if and when you setup the context in code, but not if you do it from xaml - for the sake of transparency and flexibility one should consider supporting both code and xaml.
Another approach could be to trigger something on your model from xaml when certain criteria has been met.
I believe a storyboard could be used for this approach.
/Torben Falck, Strongminds, Denmark, www.strongminds.dk

Best place to bring up new window in Model View ViewModel

I have an MVVM application. In one of the ViewModels is the 'FindFilesCommand' which populates an ObservableCollection. I then implement a 'RemoveFilesCommand' in the same ViewModel. This command then brings up a window to get some more user input.
Where/what is the best way to do this whilst keeping with the MVVM paradigm? Somehow
doing:
new WhateverWindow( ).Show( )
in the ViewModel seems wrong.
Cheers,
Steve
I personally look at this scenario as one where the main window view model wants to surface a task for the end user to complete.
It should be responsible for creating the task, and initializing it. The view should be responsible for creating and showing the child window, and using the task as the newly instantiated window's view model.
The task can be canceled or committed. It raises a notification when it is completed.
The window uses the notification to close itself. The parent view model uses the notification to do additional work once the task has committed if there is followup work.
I believe this is as close to the natural/intuitive thing people do with their code-behind approach, but refactored to split the UI-independent concerns into a view model, without introducing additional conceptual overhead such as services etc.
I have an implementation of this for Silverlight. See http://www.nikhilk.net/ViewModel-Dialogs-Task-Pattern.aspx for more details... I'd love to hear comments/further suggestions on this.
In the Southridge realty example of Jaime Rodriguez and Karl Shifflet, they are creating the window in the viewmodel, more specifically in the execute part of a bound command:
protected void OnShowDetails ( object param )
{
// DetailsWindow window = new DetailsWindow();
ListingDetailsWindow window = new ListingDetailsWindow();
window.DataContext = new ListingDetailsViewModel ( param as Listing, this.CurrentProfile ) ;
ViewManager.Current.ShowWindow(window, true);
}
Here is the link:
http://blogs.msdn.com/jaimer/archive/2009/02/10/m-v-vm-training-day-sample-application-and-decks.aspx
I guess thats not of a big problem. After all, the Viewmodel acts as the 'glue' between the view and the business layer/data layer, so imho it's normal to be coupled to the View (UI)...
Onyx (http://www.codeplex.com/wpfonyx) will provide a fairly nice solution for this. As an example, look at the ICommonDialogProvider service, which can be used from a ViewModel like this:
ICommonFileDialogProvider provider = this.View.GetService<ICommonDialogProvider>();
IOpenFileDialog openDialog = provider.CreateOpenFileDialog();
// configure the IOpenFileDialog here... removed for brevity
openDialog.ShowDialog();
This is very similar to using the concrete OpenFileDialog, but is fully testable. The amount of decoupling you really need would be an implementation detail for you. For instance, in your case you may want a service that entirely hides the fact that you are using a dialog. Something along the lines of:
public interface IRemoveFiles
{
string[] GetFilesToRemove();
}
IRemoveFiles removeFiles = this.View.GetService<IRemoveFiles>();
string[] files = removeFiles.GetFilesToRemove();
You then have to ensure the View has an implementation for the IRemoveFiles service, for which there's several options available to you.
Onyx isn't ready for release yet, but the code is fully working and usable at the very least as a reference point. I hope to release stabilize the V1 interface very shortly, and will release as soon as we have decent documentation and samples.
I have run into this issue with MVVM as well. My first thought is to try to find a way to not use the dialog. Using WPF it is a lot easier to come up with a slicker way to do things than with a dialog.
When that is not possible, the best option seems to be to have the ViewModel call a Shared class to get the info from the user. The ViewModel should be completely unaware that a dialog is being shown.
So, as a simple example, if you needed the user to confirm a deletion, the ViewModel could call DialogHelper.ConfirmDeletion(), which would return a boolean of whether the user said yes or no. The actual showing of the dialog would be done in the Helper class.
For more advanced dialogs, returning lots of data, the helper method should return an object with all the info from the dialog in it.
I agree it is not the smoothest fit with the rest of MVVM, but I haven't found any better examples yet.
I'd have to say, Services are the way to go here.
The service interface provides a way of returning the data. Then the actual implementation of that service can show a dialog or whatever to get the information needed in the interface.
That way to test this you can mock the service interface in your tests, and the ViewModel is none the wiser. As far as the ViewModel is concerned, it asked a service for some information and it received what it needed.
What we are doing is somethng like that, what is described here:
http://www.codeproject.com/KB/WPF/DialogBehavior.aspx?msg=3439968#xx3439968xx
The ViewModel has a property that is called ConfirmDeletionViewModel. As soon as I set the Property the Behavior opens the dialog (modal or not) and uses the ConfirmDeletionViewModel. In addition I am passing a delegate that is executed when the user wants to close the dialog. This is basically a delegate that sets the ConfirmDeletionViewModel property to null.
For Dialogs of this sort. I define it as a nested class of the FindFilesCommand. If the basic dialog used among many commands I define it in a module accessible to those commands and have the command configure the dialog accordingly.
The command objects are enough to show how the dialog is interacting with the rest of the software. In my own software the Command objects reside in their own libraries so dialog are hidden from the rest of the system.
To do anything fancier is overkill in my opinion. In addition trying to keep it at the highest level often involving creating a lot of extra interfaces and registration methods. It is a lot of coding for little gain.
Like with any framework slavish devotion will lead you down some strange alleyways. You need to use judgment to see if there are other techniques to use when you get a bad code smell. Again in my opinion dialogs should be tightly bound and defined next to the command that use them. That way five years later I can come back to that section of the code and see everything that command is dealing with.
Again in the few instances that a dialog is useful to multiple commands I define it in a module common to all of them. However in my software maybe 1 out of 20 dialogs is like this. The main exception being the file open/save dialog. If a dialog is used by dozens of commands then I would go the full route of defining a interface, creating a form to implement that interface and registering that form.
If Localization for international use is important to your application you will need to make sure you account for that with this scheme as all the forms are not in one module.

Resources