Displaying a WPF Window from ViewModel in C#

winprofessional 41 Reputation points
2020-08-14T07:52:57.84+00:00

I have a C#/WPF app based on MVVM pattern. The app has a window with a tool bar. On clicking a button on this toolbar, I need to show a Window like a settings window. The toolbar button is bound to a command that should load the settings window. I have designed the WPF settings window. The user will be able to select some settings(preferences) from this second window. This I understand is not like page navigation but loading the window. When the settings window is displayed the main window will be in the background. How I can I do this from the ViewModel of the main window?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,694 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Peter Fleischer (former MVP) 19,306 Reputation points
    2020-08-16T07:30:13.053+00:00

    Hi,
    in ViewModel of Main window you can call ShowDialog with Settings window instance and bind the same ViewModel instance. Try following demo:

    17809-x.png

    and ViewModel:

    Namespace WpfApp048  
      Public Class ViewModel  
        Implements ICommand  
      
        Public Property Value1 As String  
      
        Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged  
        Public Sub Execute(parameter As Object) Implements ICommand.Execute  
          Dim wndSetting = New Window048A  
          wndSetting.DataContext = Me  
          wndSetting.ShowDialog()  
        End Sub  
        Public Function CanExecute(parameter As Object) As Boolean Implements ICommand.CanExecute  
          Return True  
        End Function  
      End Class  
    End Namespace  
    
    0 comments No comments