WPF MVVM - Accessing properties of other ViewModels using delegates - c#

I have a MainViewModel, which features PersonViewModel and a HouseViewModel as properties. HouseViewModel has the property GetRooms. What is the best way to access this property from the PersonViewModel?
My solution at the minute is to pass through an instance of MainViewModel to PersonViewModel, then I can call MainViewModel.HouseViewModel.GetRooms. However, this seems a little wasteful.
I am happy to pass a function as a delegate, but I can't seem to do this with a Property. I have searched for an example of this and only come up with overly complicated techniques. I'm assuming there must be a simple way of doing this, as it seems like a common problem. Can anyone point out a strong example?
Or is there another, alternative method that I haven't considered?

If a method has to be shared across two viewmodel, it should be defined in base viewmodel or a service. The best way is a common Service class should hold all common methods like GetRooms, CheckIn, CheckOut, etc. And this service should be provided to every viewmodel using Dependency Injection.
public class HomeViewModel
{
public HomeViewModel(IRoomService roomservice)
{
}
}
public class PersonViewModel
{
public PersonViewModel(IRoomService roomservice)
{
}
}

Related

Correct way to use DI when creating new objects in Collection

MVVM, using PRISM 6 and Unity.
Bootstrapper takes care of creating intial View, which is in turn AutoWired to the ViewModel (i.e. View Model is resolved and it's DI's are taken care of).
Now the View Model has a Collection of other View Models.
This Collection can be added to with User Input, say with a button push.
The View Models in the collection require access to a singleton that I have to manage the "Workspace" (paths for image folders etc). So I would also want the creation of those objects to have that "Workspace" singleton injected into it.
In the method that would create a new ViewModel, what's the correct way to utilize DI/IoC to create it?
The only way I see it (dangerous to say "only" I know, that's why I'm asking for help) is:
Inject the Unity Container into the View Model that contains the
collection, then Resolve the new View Models as the button is hit.
The new View Models would be setup with a dependency on the
interface for the "Workspace" object.
Create a new View Model when the button is hit and pass the
"Workspace" into the constructor (of course the Workspace would need to be DI'd into the parent View Model to be passed down).
I have read multiple places that getting into passing the Container down via DI so that one can use Resolve<> isn't "correct".
Is this where creating a generic Factory would help? This still forces me to pass the container down, now it's just in the form of a factory though...
public T factory<T>(IContainer _container)
{
return _container.Resolve<T>();
}
Often when I read about DI, it is treated as the be all and end all. I more often than not use IoC heavily even in my small and simple projects, however, it is just pattern and has a place like everything else.
The Microsoft Press book Adaptive Code via C# explains SOLID well, justifies its use, covers the various forms of DI and the cost/benefit of each technique. For me, it made a lot of sense of these issues, managing project growth, and dealing with external dependencies.
I would NOT pass the UnityContainer to anything outside of my bootstrapper, other than a system which abstracts and breaks apart the bootstrapping/modularity process. In addition to the points you have made about this, Unity is a third-party dependency to your application just like anything else, and I would be very selective of which (if any) I tie myself to.
For your example above, I would use a simple factory. You could abstract this as far as you like, but a good compromise would be relieving your primary ViewModel of the burden of having to create its own children.
When using DI, there is nothing wrong with instantiating things yourself where appropriate. The most appropriate place of course is a factory. I wouldn't create a generic factory, as you stated, this is basically just like passing around the IoC container. Define a typed factory instead:
public interface IWorkspaceItemViewModelFactory
{
WorkspaceItemViewModel CreateWorkspaceItem();
}
The implementation of this might look something like this:
public class WorkspaceItemViewModelFactory
{
private readonly IWorkspaceManager _workspaceManager;
public WorkspaceItemViewModelFactory(IWorkspaceManager workspaceManager)
{
_workspaceManager = workspaceManager;
}
public WorkspaceItemViewModel CreateWorkspaceItem()
{
return new WorkspaceItemViewModel(_workspaceManager);
}
}
This class is an information expert with the single responsibility of creating WorkspaceItemViewModel instances. It has the right the use the new keyword, and have knowledge of WorkspaceItemViewModel dependencies. You may wish to insulate the ViewModel with an interface, but the value might be very little in your use case. Ultimately, you are using IoC, DI, and Interface Segregation for a reason, and when they stop delivering value to your particular application their use becomes noise.
Your view model could make use of this something like:
public class ExampleViewModel : ViewModelBase
{
public ExampleViewModel(IWorkspaceItemViewModelFactory workspaceItemViewModelFactory)
{
AddItemCommand = new ActionCommand(() =>
{
var newItem = workspaceItemViewModelFactory.CreateWorkspaceItem();
WorkspaceItems.Add(newItem);
});
}
public ICommand AddItemCommand { get; }
public ObservableCollection<WorkspaceItemViewModel> WorkspaceItems { get; } = new ObservableCollection<WorkspaceItemViewModel>();
}

Change current implementation of basic MVVM to adhere to SOLID pattern

I have been writing all my MVVM application with basic design pattern generally mentioned in MVVM examples available online. The pattern that I am following is described below:
Model
This section include DTO classes with their properties and Interfaces IDataService and like:
public class Employee
{
public string EmployeeName { get; set; }
public string EmployeeDesignation { get; set; }
public string EmployeeID { get; set; }
}
public interface IDataService
{
public Task<Employee> GetEmployeeLst();
}
Proxy
This layer contains Dataservice calls which implement IDataservice like:
public class DataService : IDataService
{
public async Task<Employee> GetEmployeeLst()
{
// Logic to get employee data from HTTPClient call
}
}
ViewModel
This layer contains ViewModel and reference to Model and Proxy layer from which all data is received:
public class BaseViewModel
{
public BaseViewModel(INavigationService nav, IDataService data, IAESEnDecrypt encrypt, IGeoLocationService geoLocation, IMessageBus msgBus, ISmartDispatcher smtDispatcher)
{
}
// This also include common methods and static properties that are shared among most of the ViewModels
}
All the ViewModel inherits BaseViewModel. Each viewModel also contains Delegatecommand which is executed when UI triggers an event. Which then fetches the data from the server by calling DataService in proxy layer and perform business logic and populates the properties in ViewModel which is binded to the view. For each View there is a VM which is binded to the Datacontext of the View.
ViewModel is also responsible for starting an animation I have used trigger to start storyboard which is binded to my enums in VM for state change of these trigger as in example in: http://www.markermetro.com/2011/05/technical/mvvm-friendly-visual-state-management-with-windows-phone-7/
View
In this layer I have all my Views, Usercontrols and business logic with implementation of certain dependencies like GeoLocation Service, AES encryption, NavigationService between Views etc.
Every View has .xaml and .xaml.cs file. In .xaml.cs file I have binded the data context of the view with VM like this:
this.DataContext = App.IOConatiner.GetInstance<DashboardViewModel>();
and from here on all binding happens.
My problem is that recently I had the knowledge that this pattern is not following a SOLID design pattern which I got know in this answer of my question:
Simple Injector inject multiple dependency in BaseClass
I am trying very hard to change my design as per the suggestion given in my previous question's answer. But I am not able to get some of the things like:
Currently View Datacontext is binded to ViewModel hence all the controls are controlled by a property in VM. How would I change this to your above mentioned pattern with Processor/Service or DialogHandler?
I am using Delegatecommands which are binded to command property of UI element. Execution of these command certain action happens like animation, usercontrol is displayed. How to do it in command pattern?
How can I start changing my current implementation to accommodate all those changes with best possible approach?
First of all an answer to your question 3
How can I start changing my current implementation to accommodate all those changes with best possible approach?
This is the very first step you need to take. It is not a case of some smart refactoring of your current code. You will need to take a step back and design the application. I once read some nice blog about (re)design.
Before starting to write any code, define how many different basic types of views you will want to show to the user? E.g.:
Just show (any type of) data
Edit data
Alert user
Ask user for input
...
When you defined your different requirements, you can translate this to specific interfaces that are tailor made for the job they serve. For example a view that lets the user edit data will typically have an interface that will look something like:
public interface IEditViewModel<TEntity>
{
public EditResult<TEntity> EditEntity(TEntity entityToEdit)();
}
Once you every detail of this design in place, you must decide how you will show your views to the user. I used another interface for this to handle this task for me. But you could also decide to let a navigation service handle this kind of task.
With this framework in place, you can start coding your implementations.
Currently View Datacontext is binded to ViewModel hence all the controls are controlled by a property in VM. How would I change this to your above mentioned pattern with Processor/Service or DialogHandler?
This will not change in this design. You will still bind your view to your viewmodel and set the datacontext to the viewmodel. With a lot of views the use of an MVVM framework like Caliburn Micro will come in handy. This will do a lot of the MVVM stuff for you, based on Convention over Configuration. To start with this model, would make the learning curve even higher, so my advice to start of by hand. You will learn this way what happens under the covers of such an MVVM tool.
I am using Delegatecommands which are binded to command property of UI element. Execution of these command certain action happens like animation, usercontrol is displayed. How to do it in command pattern?
I'm not sure if the command pattern you mention here is the command pattern I advised you in the previous answer. If so, I think you need to reread this blog, because this is totally unrelated to the commands I think you mean in this question.
Animation and that sort of stuff is the responsibility of the view, not the viewmodel. So the view should handle all this stuff. XAML has a lot of ways to handle this. More than I can explain here. Some ideas: Triggers, Dependency Properties
Another option: Code behind! If the logic is purely view related IMO it is not a mortal sin to place this code in the code behind of your view. Just don't be temped to do some gray area stuff!
For commands that just perform a method call in your viewmodel, ICommand is still possible and MVVM tools like Caliburn will do this automagically...
And still: Loose the base class....
Why are you injecting all these services in your viewmodel base class if the viewmodel base class does not make use of these services himself ?
Just inject the services you need in the derived viewmodels that do need those services.

Simple Injector inject multiple dependency in BaseClass

I have a BaseViewModel which is inherited by multiple ViewModel classes. In my BaseViewModel I have a couple of dependencies which get injected from ViewModel. Now if I need to add a new dependency in my BaseViewModel I need to change all the VM which inherit BaseViewModel. Please let me know how can it be handled in Simple Injector. Following is my code structure:
How can I make my base class injection independent so that I don't need to make changes in all my inherited class?
Code:
public class BaseViewModel
{
protected readonly IAESEnDecrypt AESEnDecrypt;
protected readonly IDataService DataService;
protected readonly INavigationService NavigateToPage;
public BaseViewModel(INavigationService nav, IDataService data, IAESEnDecrypt encrypt)
{
AESEnDecrypt= encrypt;
NavigateToPage = nav;
DataService = data;
}
}
public class ViewModel
{
public ViewModel(INavigationService nav, IDataService data, IAESEnDecrypt encrypt) : base (nav, data, encrypt)
{
}
}
My BaseViewModel Contains some of the following Interfaces whose implementation is injected through constructor:
- NavigationService
- DataService
- GeoLocationService
- SmartDispatcher
- MessageBus which implement Message Aggregator
It also Contains some common properties as static variables whose data is used throughout the application like UserDetails. And also contains CancellationToken, IsBusy to display progressbar.
BaseViewModel also contain HandleException method which handle all the incoming exceptions from all ViewModel.
Also Contains some common Commands which are used in all the Views like Si
gnoutCommand, NavigationBar Commands.
Actually it has started to contain all kinds of common methods used among various ViewModel.
Please suggest how can i refactor this code?
Your last sentence:
Actually it has started to contain all kinds of common methods used among various ViewModel
Precisely describes your problem! As Steven already described, that you're building almost the complete application through a single base class. Thereby infringing the Open-Closed principle which you are heavinly experiencing now.
The trick is design your application around very small SOLID ViewModels of which you compose the application at runtime. By splitting the ViewModels and using a UserControl as your views you can compose big complicated views for the user, while you still get all the benefits from using a SOLID design. So let’s take a look at some of your different interfaces that you implement and some of the functions you ‘handle’ in the base class:
NavigationService
This sounds like a service which controls the flow in your application. This sounds to me like your mainview(model). You could create a single MainViewModel which as a single property, let’s say CurrentView.Assuming you’re using WPF you typically would bind this property to a ContentControl. The content of this control can be everything from a single TextBlock to a complete UserControl. The UserControls can still be very complicated as they could be composed of multiple child usercontrol and so on. Using a MVVM framework (like e.g. Caliburn Micro or MVVM Light) for this is optionally but will come in handy.
It could also be an application global service with some of kind of callback or delegate function to perform navigation to a certain View(Model). It is in any case an infrastructural part of your application that deserves it own class and shouldn't be put away in a base class.
DataService
A single dataservice was the way I worked for over 10 years. Every time I hit my head against the wall. There comes a point in time that you need something special which is not included in your dataservice and you will probably go through your complete code base to make the right adjustments. Speaking of the Open-Closed principle…
Than I learned about the Command/Handler and Query/Handler pattern. You can read about this here and here. Using this pattern everywhere you need data you just inject the correct IQueryHandler<,> and use it right there. Not every view(model) needs data and certainly not the same data. So why use a global DataService? This is will also improve your Lifetime management of your DBContext object.
HandleException
Why is your base class responsible for handling the exceptions of your viewmodel? What does the base class know about this exceptions? What does the base class do? Log the exception, show a message to the user (what kind of message?) and silently continue? Letting the application break down 3 minutes later and leaving a user ignorant of what happened?
I.M.O. exception should not be catched if you didn’t expect them to be thrown in the first place. Than log the exception at an application level (e.g. in your Main), show an ‘Excuse me’ message to the user and close the application. If you expect an exception, handle it right there and then and handle according.
UserDetails
Ask yourself the question how many of your 40 ViewModels actually need this information? If all 40 are in need of this information, there is something else wrong with your design. If not, only inject this details (or even better an IUserContext) in the ViewModels that actually use them.
If you use it for some kind of authentication consider using a decorator wrapping the task they need permission for performing it.
IsBusyIndicator
Again: do you need this in every ViewModel? I think not. I think furthermore, showing the user a busy indicator is a responsibility of the View, not the ViewModel and the as the length of the task determines if you need to show this, make it a responsibility of the task (assuming you’re looking at your tasks also in a SOLID manner by using e.g. the already mentioned Command/Handler pattern).
With WPF you could define a Dependency Property that you can bind to the view, thereby showing some kind of busy indicator. Now just inject a ShowBusyIndicatorService in the task that needs to show it. Or wrap all your (lengthy) tasks in a ShowBusyIndicatorDecorator.
Design
Now let’s look at some simple interfaces you could define to build up your View(Model)s. Let’s say we decide to make every ViewModel responsible for a single task and we define the following (typical LoB) tasks:
Show (any kind of) data
Select or choose data
Edit data
A single task can be stripped down to ‘Show data of single datatype (entity)’. Now we can define the following interfaces:
IView<TEntity>
ISelect<TEntity>
IEdit<TEntity>
For each interface type you would create a Processor/Service or DialogHandler depending on your semantic preferences which would do the typical MVVM stuff like finding a corresponding view and binding this to viewmodel and show this in some way (a modal window, inject it as usercontrol in some contentcontrol etc.).
By injecting this single Processor/Service or DialogHandler in the your ‘Parent’ ViewModel where you need to navigate or show a different view you can show any type of entity by a single line of code and transfer the responsibility to the next ViewModel.
I’m using these 3 interfaces now in a project and I really can do everything I could do in the past, but now in SOLID fashion. My EditProcessor, interface and viewmodel look like this, stripped down from all not so interesting stuff. I’m using Caliburn Micro for the ViewModel-View Binding.
public class EditEntityProcessor : IEditEntityProcessor
{
private readonly Container container;
private readonly IWindowManager windowManager;
public EditEntityProcessor(Container container, IWindowManager windowManager)
{
this.container = container;
this.windowManager = windowManager;
}
public void EditEntity<TEntity>(TEntity entity) where TEntity : class
{
// Compose type
var editEntityViewModelType =
typeof(IEntityEditorViewModel<>).MakeGenericType(entity.GetType());
// Ask S.I. for the corresponding ViewModel,
// which is responsible for editing this type of entity
var editEntityViewModel = (IEntityEditorViewModel<TEntity>)
this.container.GetInstance(editEntityViewModelType);
// give the viewmodel the entity to be edited
editEntityViewModel.EditThisEntity(entity);
// Let caliburn find the view and show it to the user
this.windowManager.ShowDialog(editEntityViewModel);
}
}
public interface IEntityEditorViewModel<TEntity> where TEntity : class
{
void EditThisEntity(TEntity entity);
}
public class EditUserViewModel : IEntityEditorViewModel<User>
{
public EditUserViewModel(
ICommandHandler<SaveUserCommand> saveUserCommandHandler,
IQueryHandler<GetUserByIdQuery, User> loadUserQueryHandler)
{
this.saveUserCommandHandler = saveUserCommandHandler;
this.loadUserQueryHandler = loadUserQueryHandler;
}
public void EditThisEntity(User entity)
{
// load a fresh copy from the database
this.User = this.loadUserQueryHandler.Handle(new GetUserByIdQuery(entity.Id));
}
// Bind a button to this method
public void EndEdit()
{
// Save the edited user to the database
this.saveUserCommandHandler.Handle(new SaveUserCommand(this.User));
}
//Bind different controls (TextBoxes or something) to the properties of the user
public User User { get; set; }
}
From you IView<User> you can now edit the current selected User with this line of code:
// Assuming this property is present in IView<User>
public User CurrentSelectedUser { get; set; }
public void EditUser()
{
this.editService.EditEntity(this.CurrentSelectedUser);
}
Note that by using this design you can wrap your ViewModels in a decorator to do crosscutting concerns, like logging, authentication and so on.
So this was the long answer, the short one would be: loose the base class, it is biting you and it will bite you more and harder!
Prevent having this base class in the first place. This base class is a big code smell and the result is your current pain. Such a base class will violate the Single Responsibility Principle (SRP) and will just act as a big helper class for all derived view models, or it even seems that you are putting cross-cutting concerns in there. The base class might even hide the fact that your view models violate the SRP. They probably do too much; have too many responsibilities.
Instead, try to do the following:
Move cross-cutting concerns out of the base class into decorators or find another way to apply cross-cutting concerns.
Group related dependencies together into a aggregate service and inject such aggregate service into your view model.
In a well designed application, there is hardly ever a need for having such base class that takes dependencies.
If you aren't able to change your design (but please do take a look it this; you will be in a much better place without that base class), you can revert to explicit property injection. Simple Injector does not do this out-of-the-box, but the documentation describes how to do this.
Basically, it comes down to writing a custom IPropertySelectionBehavior, moving the constructor dependencies of the BaseViewModel to public properties and marking them with a custom attribute.
But again, only use property injection as a last resort. Property injection will only hide the design problem; it will not solve it.
You can use the ServiceLocator (anti)pattern to make the injection independent, HOWEVER you should not do this as it violates the principles of SOLID. Mark Seemann - Service Locator violates SOLID
You should rather stick to adding the dependencies in the constructor as this is in line with SOLID OO design principles.

How to access variables in a class from all forms

I have a few forms, and a class Management which has a list of users, info and stuff. I want an instace of Management which I will be able to access from all the forms. How do I do that?
Thenx in advance.
The error
Error 3 Inconsistent accessibility: parameter type 'ProjectClasses.Management' is less accessible than method 'FinaleSystem.MenuForm.Start(ProjectClasses.Management)'
means that your MenuForm is exporting a method Start (probably it is public) having a parameter of type ProjectClasses.Management that is less accessible. Probably it is internal. Declaring the Management class as public will resolve your problem. If the class is nested within another class, declare the "parent" class as public as well. If you prefer not to make the class public, make the method Start internal instead.
public means that an item is accessible from another project. internal means that the item is only accessible within the same project. If Start was public and the type of a parameter internal or private you could not call the method from another project, since you could not create an object of the requested type. You couldn't derive a class from it either in order to use it as a parameter.
Non-nested classes have a default access modifier of internal. Nested classes have a default access modifier of private.
See https://stackoverflow.com/a/3763638/880990 for details
Best way (my point of view) is to use a MVVM pattern and have the ViewModels inherit from a base class
Just to elaborate on Thomas' answer.
Singleton
A singleton is basically a class where it only ever allows the program to holds one instance of itself. In other words, whether you're in the Superman class or the Batman class, the Singleton class, let's call it MyCar will always be the same.
A Singleton is pretty easy to implement and to grasp. Take a look at this tutorial: http://www.usmaanz.com/singleton/ to get an idea.
MVVM
A MVVM pattern is pretty powerful! It allows you to create an object which contains certain amount of properties and allow that model to be used by many Views or Forms in your case.
Let's say that a Form has the following controls:
Username
Password
Email
And in this form, we wish to hold data from what is being passed in to these controls. Therefore, the following class will help us hold that data:
public class MyModel
{
public string Name {get;set;}
public string Password {get;set;}
public string Email {get;set;}
}
Then in your Form, you may do:
MyModel model = new MyModel(){Name = txtName.Text, Password = txtPassword.Text, Email = txtEmail.txt};
This object will now hold the data of the form. You may also use this class to hold data any where else and you can obviously, freely, create as many instances of it as you want.
Hope that helps!
One possible solution is to make your Management class' properties static.
Cheers
The simple case of this is implemented as a singleton where one and only one instance of a class exists for the life of the program. Singleton has many drawbacks mostly related to difficulty of testing and correctly handling threading. The next pass at solving this is usually implemented as a service locator pattern, however this has also come to be viewed as an anti-pattern. The best way to handle this is called dependency injection. While DI is the "best way" it may be hard/over kill in your scenario.

Is anything good/bad/unnecessary about this use of a public member?

Here is a synopsis of my code which is a moderately complex WinForms GUI.
The context of the dependencies is the model view presenter pattern.
public class StatSyncherFormView : Form, IView
{ ... }
public class Presenter
{
// Here is the member I made public
public readonly IView view;
public Presenter(IView view)
{
this.view = view;
}
}
static void Main()
{
IView view = new View();
Presenter presenter = new Presenter(view);
// Here is where I'm accessing the public member
Application.Run((Form)p.view);
}
1) I like the fact that view is only set by the constructor and won't be modified after. It makes me feel better in the context of multi threaded GUI development.
2) With public View {get; private set;} then I lose (immutability?).
3) With private readonly IView view I also need public View {get {return view;}} which feels (to me at least maybe someone can tell me otherwise) redundant.
My Question: I feel like (3) is the only way to avoid using a public member, but in this case I do not understand the benefit.
I realize this is minutiae, so Thanks in advance for anyone who takes the time to give me advice about this.
Just give the Presenter a Run() method.
This is really just a variant on the publicly-visible fields vs properties debate.
Following the standard guidelines (your option 3) is what most people will recommend, despite what you call "redundancy". BTW I'm not sure which of the following you mean by redundancy
a few extra characters to type, or
an extra getter method at runtime (which will probably be optimized away by the JITter).
In neither case is the "redundancy" significant.
Having said that, in your specific case Hans Passant's answer, which is to avoid the need for the property/field altogether, is probably the best.
The benefits of your third approach (which I like most) include:
You may add logic to the getter later without the need of recompiling calling code
Encapsulation: you have exactly one place in your code that gets the value from the actual field, allowing you to add logging or use any other debugging mechanism to troubleshoot unexpected behavior.
The encapsulation also means that you could actually change the field to hold some other type, as long as it can be converted to IView. This conversion can happen in the getter.
If you use public field, you cannot change it to property later without recompiling your assembly. So I think it is better to do it right at the first place by using property.

Categories