1

I am new to MVVM .I have a window Demo.xaml which has menu, under menu i have sub menus.I want to open sub menu window i.e Test.Xaml on the click of submenu using MVVM approach. I made an object of Test Window but it didn't showed "Show" property. I also tried by using Delegate Commands but i failed. How can I achieve this?

Rohit
  • 33
  • 1
  • 7
  • When you say MVVM approach, do you mean the ViewModel should be able to spawn a new window? – grek40 Jan 23 '18 at 08:10

2 Answers2

0

The most common MVVM approach to solve your problem is to bind the submenu item's "Command" to a property in the ViewModel which implements ICommand. Then, in the command's execution, you can open your window of choice.

Efi Z
  • 182
  • 12
0

You need to use ICommand - when working with MVVM using RelayCommand is best practice.

See my example below:

MainWindow.xaml

<MenuItem Header="Settings" Command="{Binding CmdOpenSetting}" >                    
    <MenuItem.Icon>
        <Image Source="..\Resources\if_Gnome-Preferences-System.png" Height="16" Width="16" Margin="0,0,-5,0" />
    </MenuItem.Icon>
</MenuItem>

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();

    //Singelton not needed
    MainWindowViewModel.Instance = new MainWindowViewModel();
    this.DataContext = MainWindowViewModel.Instance;

    //Also works
    this.DataContext = new MainWindowViewModel();
}

MainWindowViewModel.cs

private RelayCommand _commandOpenSettings;

public ICommand CmdOpenSetting
{
    get
    {
        if(_commandOpenSettings.IsNull())
        {
            _commandOpenSettings = new RelayCommand(param => OpenSettings());
        }
        return _commandOpenSettings;
    }
}

Note you may have to adjust the CmdOpenSetting according to you implementation of RelayCommand

See Example RelayCommand

Felix D.
  • 4,811
  • 8
  • 38
  • 72