Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create view object in ViewModel

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.

like image 608
Ramesh Avatar asked Sep 03 '25 09:09

Ramesh


1 Answers

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 of MainWindow.xaml.cs:

DataContext = this;

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 the Resources section (I prefer to use App.Resources in App.xaml:

<DataTemplate DataType="{x:Type ViewModels:YourViewModel}">
    <Views:YourView />
</DataTemplate>

Now wherever you 'display' a view model in the UI, the relating view will automatically be shown instead.

<ContentControl Content="{Binding ViewModel}" />

A third way is to create an instance of the view model in the Resources section like so:

<Window.Resources>
    <ViewModels:YourViewModel x:Key="ViewModel" />
</Window.Resources>

You can then refer to it like so:

<ContentControl Content="{Binding Source={StaticResource ViewModel}}" />
like image 106
Sheridan Avatar answered Sep 04 '25 23:09

Sheridan