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 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}}" />

其他提示

I have answered a very similar question previously, which details how you can open a new window from your view model, whilst maintaining the separation of concerns that the MVVM pattern promotes. I hope this helps: Open a new Window in MVVM

You are allowed to break the rule. You don't have to follow MVVM completely. I am always using commands to create a new view. You could even create an event (Amagosh, did he just say that!?) for when you click on a button. I mean, this is just my opinion, I guess it depends on the style programming you're into.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top