WPF - MVVM Screen Management - wpf

Imagine you have a complex data object. It was complex enough that to edit the various properties of the object, it would be best for the user to have multiple screens. It's essentially a shopping cart for configured items.
So one screen would allow you to add items.
Another would allow you add modifications to those items, predetermined changes that have a cost associated.
A third screen would allow you to configure global settings for your items.
As I'm sure you can guess, each screen is operating on the exact same cart, just altering different properties and relationships of the items inside.
So, we're going to try to write the application using MVVM, and while discussing the various screens (as well as navigation between them) we arrived at the following question:
How do people generally manage application state when using MVVM? The navigation bar that the users will use to change screens will exist outside of the screen, but when a user clicks it, what common ways have people been using to hide one and show another?
More generally, how are people handling global application state? The user can only operate on one cart at a time, there can only be one user logged in at a time, only one screen can be shown at a time. Would it be best to create a singleton that stored these important properties and the ViewModels could keep a copy of them and subscribe to changes via an event aggregator?
As you can tell, I barely even know where to start with this problem, so any advice at all is welcomed and appeciated.

I would use ViewModels to track the application state.
One ViewModel controls the entire application, and it handles what page the user is currently on. The application itself is bound to the main ViewModel, and the majority of the application screen space is a ContentControl that is bound to ViewModel.CurrentPage. DataTemplates are then used to determine which View to display for whatever page the user is currently on
In the past I've used a global singleton for some objects (such as current user) and the ViewModels use a reference to this if needed. So if I wanted to display the UserName on a page, I'd have a property in the ViewModel called UserName and it returns Global.Instance.CurrentUser.UserName

For your type of situation I would look into PRISM. PRISM is a collection of patterns for developing WPF applications in a loosely coupled MVVM manner.
Specifically, for your example of the multiple screens and managing application state, using a "Controller" to load the views for the various representations of your ViewModel (the cart) into separate "Regions" would probably be a good start. There looks to be a great article on MSDN about getting started with PRISM, including composing user interfaces (Regions).

Related

NavigationWindow dataflow

I am writing my first wpf application now .
I want to use a NavigationWindow on each page the user make selections and all the data should be available on the next pages, I have about 6 page.
How I should path all the data ? via the constructor ? or there is some smarter way in WPF .
On the last page there will be a lot data to path from the previous pages.
I would attack this from one of two ways: The Code-behind way (Easy, but difficult to expand, also will get very messy), and the MVVM way (Takes some learning, separates concerns, easy to extend, manage).
In the code-behind way, I would just have a Tab control with the tab headers styled the way you want them (you can style them to look like just about anything you want). In the code-behind you could have some logic that specifies that X Tab is not enabled or Visible until Y criteria are met.
There is a better way, but it comes with a bit of a learning curve, the MVVM design pattern. You would have 6 Page objects that are really just CLR objects that define the contents of the page (e.g. if it is a questionnaire your page objects would contain question objects and title objects for instance).
You could have a couple of Views, a navigation View, and a page view. The NavigationView would be bound to a NavigationViewModel which would have the logic necessary to change the page. The PageView would be bound to one of 6 PageViewModels and the PageViews DataContext (which provides that binding) could be changed based on the NavigationViews logic.
Learning Prism composite application guidance for WPF Silverlight MVVM Fundamentals
MSDN Page for MVVM explanation
Night Walker,
It is difficult to make out exactly what you want to do from your explanation. First, the NavigationWindow is the frame of your application, I think you know this but I just wanted to make sure we understood that we're not creating new instances of the NavigationWindow. I think you mean 'Pages'. Pages are the content of a Navigation window and represent some target that you want to appear in the ContentPresenter that is provided by the NavigationWindow.
I'm again not sure how you are using the phrase 'Path the data'. Typically you would create Pages either directly in the project or in satellite projects and then reference them using Pack URIs. An example of how Pack URIs are constructed can be found here.
http://msdn.microsoft.com/en-us/library/aa970069(v=vs.85).aspx
You can then navigate to the pack URLs using an expression that looks like:
this.Navigate(new Uri("pack://application:,,,/MyAssembly;component/MyPage.xaml", UriKind.Absolute);
If you don't want to get involved with all the nuts-and-bolts of the framework for navigation and just want to focus on the application for your users, you can check out the professional version of the NavigationControl that I put together:
http://www.teraque.com/products/explorer-chrome-suite/
There's an free demo you can download. If this is was you are looking to do I can give you pointers if you don't want to purchase the package directly.
Sincerely,
Donald Roy Airey
donald.roy.airey#teraque.com

MVVM: One ViewModel structure for all Views vs. separate ViewModel structure per View?

I'm new to MVVM and need a bit of help.
My application consists of a number of different windows which display controls allowing the user to edit the data in the Business layer.
At the moment, each time the user opens a new instance of one of these windows, a ViewModel structure - classes and collections mirroring the Business layer - is created from scratch and databound to the View on the window, and is also configured to access the appropriate parts of the Business layer.
This is quite sluggush at the moment, and I have a suspicion it is because the application has to wait until all the new ViewModels are created and configured every time a window is opened. I also notice the RAM gets munched up quite quickly too.
Would it be better to have a single ViewModel structure which is created when the application starts, and then all windows and controls refer to this single instance? What is the convention for MVVM?
One ViewModel per view is pretty standard. You don't want to share instances of ViewModels, since they are (usually) stateful.
I would look deeper into the sluggishness before concluding it's the creation of the ViewModel that's causing it. Profile the application with a tool, set some stopwatches, or debug the app and see what the bottleneck is.
do you need to recreate your viewmodels every time you access your views?
if not it seems you use view first approach, maybe you should then use a viewmodel locator?
you can also take a look at viewmodel first approach, maybe this fits more in your application.

How to design a wpf application with multiple interfaces

I'm trying to learn how to design an application which has several different user inferfaces. its an application where a doctor can view patient records, write prescriptions and so on. when designing this one(including the login) I have created seperate user controls for login, prescription writing, medical history browing and set all of their visibility to hidden and then I've put all of them in a single stack panel on the main application window. I'm thinking to display the appropriate usercontrols using the help of code-behind files.
I would like to know is this a valid way of creating wpf applications, or how you would do in desining applications with multiple interfaces (I'm plaining to use some animations on them, such as fade in and hide when closed a user control ).
Thank you.
For a simple project this is perfectly fine.
However as the number of views grow, you might want to design a system for managing this stackpanel.
There is a library designed to handle these kind of situations, you can find it here: http://compositewpf.codeplex.com/ look at the stuff called RegionManager

Sharing state/changes across ViewModels

I have an App which has a Tasks tab and a Projects tab. I decided to make a separate ViewModel for each of the tabs, TasksViewModel and ProjectsViewModel.
The Tasks tab has a new task area with an associated project pulldown and the Projects tab (obviously) has a list of projects.
What I'd like is for the pulldown on the Tasks tab to share the same collection as the Projects tab list so that any time I add or remove a project on the Projects tab the list on the Tasks tab is up to date automatically. This worked well with a single ViewModel but it was beginning to become quite unruly.
Should I not have split into two ViewModels? Is there a common method of sharing data like this? Perhaps pass the same ObservableCollection<Project> into each of the ViewModels? Perhaps some type of notification back to the TasksViewModel along the lines of ICollectionChanged.
Appreciate any insight/input!
The easiest solution here is often to use some form of Messaging Service to pass information between the two ViewModels.
For example, the MVVM Light Toolkit provides an IMessenger interface for situations like this.
Using a good IoC or DI toolset can help in this situation, as well. That would let you inject the project collection dynamically into both of your ViewModels, allowing a shared collection to be used in both Views.
It seems to me that your concepts of "Tasks" and "Projects" are part of your model, not part of your view model.
Consider this conceptual exercise: Suppose your app was written so that two users could use your application on two separate machines against a shared database, and one user adds a Project:
Would it be a good or a bad thing if the Project immediately showed up in the dropdown on the Tasks tab of the other user's screen?
Would it be a good or a bad thing if the Project showed up in that dropdown after the first user hit "Save" or "Commit" or "Ok"?
If the answer to either of these questions is "a good thing", your data is really part of your model not your view model. And it should be handled as such.
Your view model should incorporate your actual model by reference, and it is a good thing to share the model objects between view models as much as possible. In fact, ideally most of your application has a single set of model objects. The exception might be a dialog box where you want to be able to make some changes but then hit "Cancel" and not save them. In that case, the "Ok" button would copy data from the model maintained by your dialog box into the main application model. In this case the model objects used by the dialog and by the main application are different instances of the same class.
Now let's consider the case where you answered "a bad thing" to both of these questions. This would be an application where you never save your "Projects" list back to the main database/document/whatever, but it is a transient list used only for temporary work. In that case it would really be a view model, and I would attach it to the application (or whatever scope was appropriate) and have the two tabs access it.

WPF Frame accessing parent page controls

I have a WPF page that contains a Listbox and a frame. The frame has various pages loaded into it determined by the selection within the Listbox.
Each page within the frame has a variety of different input boxes and has a Save Cancel button. When the Save button is clicked I need the content to be saved to the database and the Listbox in the parent page to be refreshed to reflect the new data.
Saving the data is easy but how do I initiate a refresh on the contents of the Listbox in the parent page when calling it from the page that inside the frame?
I need to somehow be able to access the parent pages controls to do this.
Any ideas?
It is technically possible to reach up into the parent control and have your way with the controls it contains, but it makes for code that's very difficult to maintain because if you change the structure of the parent control, you break code in all of the contained pages. That would be considered a very tightly-coupled design and it's often fragile.
A somehwat cleaner design would be to have your page classes raise an event when the Save button is pressed. Then your parent frame can sink the event and refresh whatever it knows needs to be refreshed after a save operation. That's easier to maintain because your components are more loosely coupled, but it still puts a lot of database knowledge into your GUI components. Such a design might be appropriate for a relatively simple app on which you don't expect to do a lot of maintenance or future enhancements.
The design pattern I prefer (as do many developers) is to isolate the database handling and business logic inside one or more classes with a simple programmatic interface that can be tested easily. The GUI components are kept as simple and thin as possible, so they can be easily changed if necessary. This is often called a Model-View-Controller pattern but there are other names for it. In your example, the "controller" class that encapsulates your business logic would have properties and methods for reading and setting information, and a "Save" or "Commit" method that writes changes to a database. Once the save is complete it would raise a "Saved" or "Changed" event that notifies all controls ("views") displaying information that the information has changed and they would refresh themselves based on the new values of the properties of your controller class.

Resources