How to show a View from a ViewModel and also set the data context of that view in WPF with MVVM

StackOverflow https://stackoverflow.com/questions/22332363

  •  13-06-2023
  •  | 
  •  

Question

How to open a new View(Dialog) from a view model command and also set the new view's data context with its view model. this question is bothering me a lot, although there has been so many question on this but I could not get satisfied with any of the answer so far.

So, suppose:

I have a start up dialog called MainView and I show this dialog and set its data context in App.xaml.cs (OnStartUp) method. In MainView, there is a button called "open a new dialog" and this button's command is bind with a delegate command in MainViewModel. So, when user hits this button, then command calls the execute method.
Let's say command in MainViewModel which is bind with button in view is as following

  public ICommand ShowNewDialogCommand
    {
       if(this._showNewDialogCommand == null)
        {
          this._showNewDialgoCommand = new DelegateCommand(ShowDialogFromVM);
        }
    }
    private void ShowDialogFromVM()
    {
    }

And let's say the new dialog that I want to show is ListAllStudentsView and its ViewModel is StudentsViewModel. So, what are the various approaches of showing this dialog without breaching the MVVM pattern? And what are the merits and demerits of each approach?

Was it helpful?

Solution

First, we need to create a view (somewhere) with its datacontext set. Easy enough, we instantiate the view and either pass it the view model (assuming the view sets its data context in its constructor) or set it manually. The view could also have declared the view model in XAML if we so desired.

Method 1:

Window dialog = new ListAllStudentsView(new StudentsViewModel());

Method 2:

Window dialog = new ListAllStudentsView();
dialog.DataContext = new StudentsViewModel();

Method 3:

<Window.DataContext>
   <local:StudentsViewModel/>
</Window.DataContext>

Now we need to put this code (and the associated dialog.ShowDialog() somewhere). I see two options, right in the command's execute function, or in the view's code-behind (triggered by an event raised by the command's execute function like "RequestDialog").

I prefer the first, even though it doesn't adhere as rigidly to MVVM because it is a lot simpler, less code, and easier to manage. If you want to be very strict about adhering to MVVM however, I would have the ViewModel raise an event like "RequestDialog" in the command function that the view listens to and runs the constructor and ShowDialog() function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top