I have the following code in my C# WPF MVVM application.
public RelayCommand PolishCommand
{
get
{
polishcommand = new RelayCommand(e =>
{
PolishedWeightCalculatorViewModel model = new PolishedWeightCalculatorViewModel(outcomeIndex, OutcomeSelectedItem.RoughCarats);
PolishedWeightCalculatorView polish = new PolishedWeightCalculatorView(model);
bool? result = polish.ShowDialog();
if (result.HasValue)
{
But i came to know that, calling a window from viewmodel is wrong one in MVVM pattern.
Also stated in the below link.
M-V-VM Design Question. Calling View from ViewModel
Please help me anybody by providing an alternate solution.
Thanks in advance.
You are right that generally you should never access views from view models. Instead in WPF, we set the
DataContext
property of the view to be an instance of the relating view model. There are a number of ways to do that. The simplest but least correct is to create a new WPF project and put this into the constructor ofMainWindow.xaml.cs
:In this instance the 'view model' would actually be the code behind for the
MainWindow
'view'... but then the view and view model are tied together and this is what we try to avoid by using MVVM.A better way is to set the relationship in a
DataTemplate
in theResources
section (I prefer to useApp.Resources
inApp.xaml
:Now wherever you 'display' a view model in the UI, the relating view will automatically be shown instead.
A third way is to create an instance of the view model in the
Resources
section like so:You can then refer to it like so: