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?

1
  • When you say MVVM approach, do you mean the ViewModel should be able to spawn a new window? Commented Jan 23, 2018 at 8:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.