Sharing state/changes across ViewModels - wpf

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.

Related

marionette create sub menu in one of menu tabs

I work on site admin application and use marionette. And my problem is - how to organize views and applications for next requirements. Thanks for any help!
There are main menu on header - Users management, Evenets, General settings
And when user clicked to Users management On main region must shows additional menu with
Users Groups Permissions items and by default list of users (first tab is active).
Each item on click should shows coresponding view with list of entities.
And my question is how to organize applications, views and interaction between them?
Is sub menu part of users list view or it independent view? Which type of marionette view it must be?
Sounds a lot like typical web page where it would be much easier to just render HTML on the backend and not build a web-application.
As for structure, there is no one correct way, but I found these couple example projects as decent start to evaluate the best structure:
https://github.com/derickbailey/bbclonemail
https://github.com/Foxandxss/bbclonemail
https://github.com/brian-mann/sc02-loading-views
They all use slightly different structure and coupling. You have to decide yourself which one is best suited for your case.
In your case I guess main application with main region where you show different sub-applications based on user selection (tabs). For specific interaction patterns look at the examples. Try to decouple everything, don't pass around references instead emit and listen to events.
I've built and work with couple bigger web applications and I recommend to no go that path unless there is a reason to do that. Admin interface sounds like something you can "quickly" setup using existing frameworks like django-admin, flask-admin, Rails scaffolding, express-admin, well you get the idea. Then again I don't know anything about the project.

How should I implement multiple views on the same data?

I have a MVVM/WPF based application that can have multiple workspaces (basically containing a TreeView) open at the same time that display and operate on the same data tree. I need to be able to expand and collapse and select the items in each workspace independently and I want to be able to drag and drop items between the two workspaces (e.g. for moving or duplicating items). I also need data virtualization in that the data is only loaded (in both views) when a tree item is expanded for the first time. There is also one workspace-wide details view that shows the details of the selected item of the workspace that currently has the focus. Workspace specific expansion and selection of items must also work programatically.
Could you layout a ruff design for a MVVM based application that embraces theses features? Should I create a separate ViewModel tree for each workspace and implement a Model-ViewModel mapper? Or should I have just one ViewModel tree with two Views? How does the details view know what is currently selected and what workspace has the focus? ...
So to rephrase my question: The Model instances displayed in each View are actually the same instances. But should the ViewModels be the same too? Or better: Could I possibly get away with that?
Also: Is there an open source application I could study that has most of these features? Could Prism or any other MVVM based framework do most of that work for me?
There is a direct correlation between View and ViewModel. The View shows a visual representation of the Model, hosted and "formatted" by the ViewModel.
Since you will have different Model (data) on each View, you need to have several instances of your ViewModel hosting each set of different data.
Now the question is: do your ViewModels share some entities or objects between them ?
If yes, could they change during your application lifetime, and do you want to see these changes in realtime in your TreeViews ?
You then have two options:
Directly bind the model to the View (if the model implements INotifyPropertyChanged) by exposing it through your ViewModel: then all your views will be automatically updated when a model property changes.
Create a component which supervises Model modifications and notify ViewModel exposing them.
The second solution is more pure than the first one because Models should be POCO and shouldn't implement some plumbing oriented-interface. ViewModel should handle the plumbing.
However it's more complicated to design, and 90% of the time, you will end-up saying "come on, just one little interface doesn't hurt" :)
For your details view. You can communicate between your TreeViewModel and your DetailViewModel using a mediator (Messenger in the MVVM Light Toolkit), which is basically a low-coupled event-oriented component. Or use a supervisor which is injected in all your ViewModel and notify them using events.
Speaking of MVVM framework, and for common architecture like the one you are describing, I would recommend the MVVM Light Toolkit.
Maybe I am missing something, but is it not possible to have 2 instances of the same View / ViewModel loaded with different data?

WPF - MVVM Screen Management

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).

Sample data in expression Blend while in design mode and live data when running the application

I have a service that returns an observable collection of persons that will be used to display the person name in a list box in my Silverlight application.
While designing the list box, the designer used sample data. However, when the xaml reaches the developer working on the view model and the service that returns an observable collection of persons to be displayed, there are some changes that need to be done.. like remove all bindings to the sample data, plug in the observable collection persons properties.
So my questions are:-
Is there a way to do this in a way where in design mode it shows the sample data and when it runs it shows the service data?
Is there a way for it to return service data while in design mode itself?
Does the designer using Expression Blend need to know what properties of the observable collection {persons} will be bound to the list box?
I would want to do this in an MVVM friendly manner {without using MVVM Light toolkit}.
Thanks for your time...
Loads of good examples out there:
http://blogs.msdn.com/b/avip/archive/2010/12/06/the-simplest-way-to-do-design-time-viewmodels-with-mvvm-and-blend.aspx
http://karlshifflett.wordpress.com/2009/10/28/ddesigninstance-ddesigndata-in-visual-studio-2010-beta2/
It's very simple. Lots of other resources on google if you need them
Edit based on comment
2. Is there a way for it to return service data while in design mode itself?
Possibly but I've not seen it. In my mind you probably wouldn't want to do this for many reasons.
You may get a delay before your data
shows up which could get quite
frustrating if you need to make a lot
of small changes.
You have a reliance on services being
available which is going to make you
even more unproductive if they ever
go down.
You or a designer doesn't have any
control over changing what is
displayed on an ad-hoc basis. At
least using the sample data system
you can change values to test
different scenarios without having to
get services data changed.
3. Does the designer using Expression Blend need to know what properties of the observable collection {persons} will be bound to the list box?
The designer/developer workflow is a tricky one. Obviously each project will be different, but having just finished a design heavy wpf project I can tell you that our designers want as little to do with Blend as possible.
The workflow that has worked for us, is for the developers (we have a front end team that work at the view/viewmodel level and backend team that build up the model and service layer) to build up the views as best they can. That means building the layout, composing the controls, adding most of the design and hooking up the bindings. We then had a designer who had experience in using Blend (there aren't many) delve in and tweak the designs to get them exactly as they wanted.
This way they had very little to do with the main brunt of the work and we could keep clean and organised views (something few designers would have the experience to do). The designers didn't really have to know anything about domain objects. It all worked very well once we'd worked out how it was going to work. Having the designers build up the views themselves would have been a nightmare in my opinion... and not something they'd have enjoyed either.

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.

Resources