I am developing an app in which I have used Prism Framework. I have registered viewmodels in bootstrapper as below:
ViewModelLocationProvider.Register<LoginControl, LoginViewModel>();
ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
ViewModelLocationProvider.Register<CountryList, CountryViewModel>();
I have also register prism for Navigation as:
builder.RegisterTypeForNavigation<LoginControl>();
builder.RegisterTypeForNavigation<MainWindow>();
builder.RegisterTypeForNavigation<CountryList>();
Its working perfect but I found that the constructor for each viewmodel is called once while first time navigating to ViewModel. After that same object of viewmodel is served. But I want that after navigation, viewmodel should also dispose and new object is served every time.
I want to achieve some this similar to autofac:
builder.RegisterType<ModuleLoader>().InstancePerDependency()
But I dont found any method in ViewModelLocationProvider to achieve this. Is there any way to achieve this?
Update
Found that when I navigate from one view to another then the view is also not disposed. We I move to same View (Usercontrol in Region) then same object is served which is the real cause for same instance of ViewModel. Is there any way to dispose view after navigation in Prism?
Resolved the issue by implementing IRegionMemberLifetime interface to my usercontrol and adding below property
public bool KeepAlive
{
get
{
return false;
}
}
Related
I programming a WPF GUI that uses multiple Views. I am using the MVVM Light Toolkit to implement the MVVM pattern.
For Navigating i use this mechanism by changing my main frame to a NavigationWindow and all my views to Pages.
I injected the navigation service in the ViewModel constructor and now I can navigate between the views.
However, i would like to transmit data between the views while navigating. There is a method from Navigation Window that makes this possible through event handlers. I already implemented a method into my Interface but I'm having problems calling the event handler on the navigated View Model.
Can anyone tell me how to call the event handler inside my ViewModel?
Thanks!!
Edit: I tried calling:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
}
But i get an error saying:
OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs)': no
suitable method found to override
I already cleaned my solution and tried a rebuild...
Any ideas?
Edit2:
So i found out that in WPF .Net 4.5 the OnNavigatedTo event is gone. What i couldnt find out why and how i could call something similiar.
I haven't gotten an answer to my question so I will attempt an answer...
Don't over think this...if one needs to transfer information either create a static link to the VM(s) in question, or set aside a static drop on the app class. Either way when a view is shown, subscribe to one of the initialization/load events and pick up the information at the predetermined location.
I am building a large scale WPF app - kind of a desktop that hosts multiple modules such as multiple Terminal windows over RS232/Ethernet, Register analyzer, automation tools, etc.
I am working with MVVM architecture where my view (XAML) instantiate the corespondent viewmodel in its resource section. and the view model is set in the data-context of the view.
in this method the view created first.
however, I red about another method called VM first, meaning view model is instantiated before the view, and I understood the theory that stands behind it. What I didn't understand is when and who instantiate the view and how it happens without coupling to the view.
I'll be more than happy to hear your thoughts, and please if someone can supply code samples it would be great..
Thanks in advance.
I'm using MVVM heavily in my projects and can share my view on this.
In my projects the view never instantiates any VM. Usually I have some kind of manager which takes care that the corresponding VM is created.
This I'm assign to the datacontext of some top-level UI control (Window for instance). The view is always defined by a style where the target type is set to the type of the view model.
The startup code just creates a Window and the main viewmodel. The VM is assigned and the rest is done by the WPF (.net) runtime so to say.
So I have a large style file, where all the styles for each viewmodel defines the corresponding view (usually a usercontrol).
This is the way I'm doing things, there are for sure others too.
hth
In my WPF / MVVM applications I use ViewModels with two constructors - one for design time (no paramaters - mock version of required components are set directly) and another for runtime (required components are injected as parameters via IoC). This allows for (mock) data to be displayed inside the Visual Studio designer for UI testing purposes.
So the simple case looks like ...
public class MainViewModel : ViewModelBase
{
private IDataFactory _DataFactory;
public MainViewModel()
{
_DataFactory = new DesignTimeMockDataFactory();
LoadData();
}
[PreferredConstructor]
public MainViewModel(IDataFactory dataFactory)
{ _DataFactory = dataFactory; }
public void LoadData()
{ DataItems.AddRange(_DataFactory.GetDataItems()); }
public ExtendedObservableCollection<DataItem> DataItems { get; private set; }
}
The design time usage can be set directly in the XAML ...
<Window x:Class="MainView"
d:DataContext="{d:DesignInstance Type=MainViewModel, IsDesignTimeCreatable=True}"
...
The run-time ViewModel is set in the code behind of the View ...
public MainView()
{
InitializeComponent();
var viewModel = SimpleIoc.Default.GetInstance<MainViewModel>();
DataContext = viewModel;
Loaded += (s, e) => viewModel.LoadData();
}
The View's Loaded event is set to call the LoadData() method of the ViewModel to trigger data loading, once the View is displayed. If LoadData() is slow, it can be changed into an async method to prevent the UI from blocking.
For those of you complaining that this is a too tightly coupled construct, my view is that is exactly how they are supposed to be. Although the View and ViewModel are separate entities, each View knows exactly what type of ViewModel it requires, and that's unlikely to change over the project development life-cycle. Using a Locator type class to hide the ViewModel constructor calls is an unnecessary level of abstraction in my opinion.
To decouple the view from the view-model, something else needs to instantiate the view model and manage its lifetime and sharing. That job might fall to an IoC container, or simple, manual dependency injection. It's entirely up to you.
E.g. from Paul Stovell's article:
public CalculatorView(CalculatorViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
It all depends on you're trying to achieve by decoupling. One reason might be so that you can have multiple views over the same view-model - in that case, whatever creates the views needs to also create the view-model.
Another may be to swap the view-model of an existing view out with another view-model without destroying the view. In that case, maybe you already have two existing view-models and you assign them to the view's DataContext as required.
view.DataContext = viewModels[0];
view.DataContext = viewModels[1];
when your application grows you usually face these decisions. Usually you have "always" both elements together the View and the ViewModel it's not about what comes first it's more like what will you use to instantiate the two elements (view and viewmodel).
For larger projects, when I had the need, I used a class called ViewModelResolver. It obviously has an interface IViewModelResolverso it can be injected nicely.
It can either return a ViewModel based on convention based on type or a string representation and uses reflection to instantiated it.
You can also pass in a ViewModel (or type) and get the matching view with the passed in view model as DataContext (view ViewModel marriage) or you can define other custom scenarios that you need for instantiating either view or ViewModel.
hope that helps
So the main point is to have an intermediate class that acts like some sort of factory service that takes car of bringing views and view models together and instantiate them.
This gives you more freedom and a good place to separate out those decisions from the ViewModel directly.
I have a view (I'll call it MainView) that contains a TabControl. The views that make up the TabItems are created using prism view discovery in MainView's ViewModel. Each of the views that are "tabs" have some cleanup that needs to be done (detaching event handlers, etc.) when I'm done with the tab control (i.e. during the MainView's Unloaded event). However, I can't do the cleanup with the Tab views' Unloaded event, as this is called when just switching tabs.
MainView is calling a method on its ViewModel when Unloaded fires, but that ViewModel does not have a reference to the Views or ViewModels that make up the tabs due to the way those views are registered. What is the proper way to clean up after my "discovered" tab views?
I have a similar situation, but we are using a Dock control where the views are loaded using Prism. So, in the Shell Views code behind unloaded event, we loop over the open Views and get the ViewModel for each view. All of our ViewModels inherit from a base ViewModel that has a virtual bool CanClose method that returns whether the view can close or not. The base ViewModel just returns true. This method is used to check if there are validation errors, unsaved changes, etc. So, then you would override this method and perform the clean up your talking about. If all of the views return true, then you could call the main shell viewmodel unload, if not then you can cancel the main view from unloading.
foreach (var doc in dockManager.Documents)
{
if (!doc.CanClose())
{
e.Cancel = true;
return;
}
}
We ended up using a message via the EventAggregator to clean up the sub-views.
I use Prism navigation in my application, and faced the same issue.
To address the problem, in the parent view model, in the OnNavigatedFrom method, I close all the views in the TabControl's region:
public class ParentViewModel : INavigationAware
{
...
public void OnNavigatedFrom(NavigationContext navigationContext)
{
var region = RegionManager.Regions["TabsRegion"];
foreach (var view in region.Views)
region.Remove(view);
}
}
Imagine a simple scenario with a WPF window containing a button and some clear space. Clicking the button creates a new custom/user control and places it somewhere randomly on the window.
Clicking one of these controls will remove it from the window.
So now I have a ViewModel ala MVVM which exposes an ICommand for the "create new" button, but where does the code to create the new control live? Each control will probably have its own ViewModel which will handle its deletion and positioning I guess.
Can it be achieved with no code behind on the window AND no real knowledge of the View by the ViewModel?
The code that causes the controls to be created lives inside your "main" ViewModel.
The code that actually creates the controls is the container.
So it would go something like:
void AddControlCommandExecuted() {
var container = // resolve your DI container here
// Now use the container to resolve your "child" view. For example,
// if using UnityContainer it could go like this:
var view = container.Resolve<ChildView>();
// Of course you can also resolve the ViewModel if your program is
// "ViewModel-first" instead of "View-first".
// Does the ChildViewModel need some properties to be set?
var viewModel = (ChildViewModel)view.DataContext;
viewModel.StringProperty = "blah";
// Now get a reference to the region in your View which will host
// the "child" views.
var regionManager = container.Resolve<IRegionManager>();
var region = regionManager.Regions["MyRegionName"];
// Finally add the view to the region. You can do it manually, you
// can use the concept of "navigation" if your MVVM framework has one
// (I 'm using Prism, which does), etc etc.
region.Add(view);
}
Update: When writing the answer, I forgot that not all MVVM frameworks have Regions as Prism does. So excuse the specificity of the code above, as it doesn't really change anything. You simply need to build something like the Region abstraction yourself. Let's see:
class MyViewModel {
public event EventHandler<ChildViewModelAddedEventArgs> ChildViewModelAdded;
}
MyView would then attach an event handler to this event, and pick up the ChildView instance from inside ChildViewModelAddedEventArgs so that it can be added to an ItemsControl it is the parent of without your ViewModel messing with such details.
Of course this means that you now need some code-behind, but this cannot be helped unless you are using a framework that provides such services itself.
This SHOULD be doable with some very careful databinding on an ItemsControl, not sure how you would achieve the layout, but you will have a parent view model containing a collection of child view models, layout would then be preformed by the ItemsControl. When the parent ViewModel created the child ViewModel, it should inject a RelayCommand as a lambda expression to remove and cleanup the child ViewModel from the parents collection.
I've been doing the best I can to try to stay true to the separation recommended by the MVVM pattern. One thing I haven't figure out how to do correctly has to do with initializing my UserControls.
My most recent example of this has to do with a library that I wrote to talk to some low-level hardware. That assembly happens to have a UserControl that I can simply drop into any GUI that uses this hardware. All that is necessary for it to work is to set a reference to the object that has access to the low level methods.
However, that's where my problem lies -- currently, the UserControl is added to the GUI via XAML, where I define the namespace and then add the UserControl to my window. Of course, I have no control over its creation at this point, so the default constructor gets called. The only way to set the necessary reference for hardware control involves calling a method in the UC to do so. The ViewModel could feasibly call a method in the Model, e.g. GetController(), and then call the method in the UserControl to set the reference accordingly. The GUI can pass a reference to the UserControl to the ViewModel when said GUI creates the ViewModel, but this violates MVVM because the ViewModel shouldn't know anything about this control.
Another way I could deal with this is to not create the UserControl in XAML, but instead do it all from code-behind. After the ViewModel gets initialized and retrieves an initialized UserControl (i.e. one that has the low-level object reference set), it can set the Content of my Window to the UserControl. However, this also violates MVVM -- is there a way to databind the Content of a Window, TabControl, or any other element to a UserControl?
I'd like to hear if anyone has had to deal with this before, and if they approached it the first or second way I have outlined here, or if they took a completely different approach. If what I have asked here is unclear, please let me know and I'll do my best to update it with more information, diagrams, etc.
UPDATE
Thanks for the responses, guys, but I must not have explained the problem very well. I already use RelayCommands within the UserControl's ViewModel to handle all of the calls to the hardware layer (Model) when the user clicks in the control in the UserControl itself. My problem is related to initially passing a reference to the UserControl so it can talk to the hardware layer.
If I create the UserControl directly in XAML, then I can't pass it this reference via a constructor because I can only use the default constructor. The solution I have in place right now does not look MVVM-compliant -- I had to name the UserControl in XAML, and then in the code-behind (i.e. for the View), I have to call a method that I had added to be able to set this reference. For example, I have a GUI UserControl that contains the diagnostics UserControl for my hardware:
partial class GUI : UserControl
{
private MainViewModel ViewModel { get; set; }
public GUI( Model.MainModel model)
{
InitializeComponent();
ViewModel = new MainViewModel( model, this.Dispatcher);
ViewModel.Initialize();
this.DataContext = ViewModel;
diagnostics_toolbar.SetViewModel( ViewModel);
user_control_in_xaml.SetHardwareConnection( model.Connection);
}
}
where the outer class is the main GUI UserControl, and user_control_in_xaml is the UserControl I had to name in the GUI's XAML.
Looking at this again, I realize that it's probably okay to go with the naming approach because it's all used within the View itself. I'm not sure about passing the model information to user_control_in_xaml, because this means that a designer would have to know to call this method if he is to redo the GUI -- I thought the idea was to hide model details from the View layer, but I'm not sure how else to do this.
You will also notice that the main GUI is passed the Model in the constructor, which I assume is equally bad. Perhaps I need to revisit the design to see if it's possible to have the ViewModel create the Model, which is what I usually do, but in this case I can't remember why I had to create it outside of the GUI.
Am new to MVVM myself but here's a possible solution:
Create a property in your VM that is of the object type (that controls the hardware) and bind it to an attached property on your UserControl. Then you could set the property in your VM using dependency injection, so it would be set when the VM is created. The way I see it, the class that talks to the hardware (hardware controller) is a service. The service can be injected to your view model and bound to your UserControl. Am not sure if this is the best way to do it and if it is strict enough to all the MVVM principles but it seems like a possible solution.
if your question is: How do i show my viewmodel in the view? then my solution is always using viewmodelfirst approach and datatemplates.
so all you have to do is wire up your viewmodel via binding to a contentcontrol.content in xaml. wpf + datatemplates will do the work and instantiate your usercontrol for your viewmodel.
You are right, the ViewModel shouldn't know about anything in the View - or even that there is such a thing as a View, hence why MVVM rocks for unit testing too as the VM couldn't care less if it is exposing itself to a View or a test framework.
As far as I can see you might have to refactor things a little if you can. To stick to the MVVM pattern you could expose an ICommand, the ICommand calls an internal VM method that goes and gets the data (or whatever) from the Model, this method then updates an ObservableCollection property of the data objects for the View to bind to. So for example, in your VM you could have
private ICommand _getDataCommand;
public ICommand GetDataCommand
{
get
{
if (this._getDataCommand == null)
{
this._getDataCommand = new RelayCommand(param => this.GetMyData(), param => true);
}
return this._getDataCommand;
}
}
private void GetMyData{
//go and get data from Model and add to the MyControls collection
}
private ObservableCollection<MyUserControls> _uc;
public ObservableCollection<MyUserControls> MyControls
{
get
{
if (this._uc == null)
{
this._uc = new ObservableCollection<MyUserControls>();
}
return this._uc;
}
}
For the RelayCommand check out Josh Smiths MSDN article.
In the View you could either call the ICommand in the static constructor of your UC - I am guessing youwould need to add an event in your class for this - or call the ICommand from some sort of click event on your UC - maybe just have a 'load' button on the WPF window. And set the databinding of your UC to be the exposed observable collection of the VM.
If you can't change your UC at all then you could derive a new class from it and override certain behaviour.
Hope that helps a bit at least, like I say, have a look at Josh Smiths MVVM article as he covers the binding and ICommand stuff in there brilliantly.
If you set the DataContext of the Window or UserControl containing thisUserControl to the main view model, the user control can call SetHardwareConnection() on itself in its Loaded event (or DataContextChanged event handler).
If that's not possible because you're saying the UserControl is 'fixed', you should derive from it or wrap it up in another UserControl, which would serve as a MVVM 'adapter'.
(In order to bind the window: you could make the MainViewModel a singleton with a static Instance property and use DataContext="{x:Static MyClass.Instance}". A nice way to get things going quickly)
Note; this is based on my understanding that MVVM works because of Bindings.. I always bind the control to a ViewModel, not pass a ViewModel as a parameter.
Hope that helps!