Lewis Heslop
Lewis Heslop

Reputation: 590

MVVM WPF; Execute a command on window shown

I am having trouble properly referencing a command or something like that.

I have a main window that contains a workspace (tabcontrol usercontrol) area. Normally workspaces are instantiated by a command in the main window viewmodel which is called by a button on the main window. What I want to do is to call for a workspace, known as StartUpView, to be instantiated on Start Up (IE When the main window is shown) and not accessible by any other means. To do this, I am going to call the command (showstartupview) right after the window is shown. I have tried to do this by putting the command right after window.show in the app.cs file, like so;

            window.Show();
        MessageBox.Show("THIS IS A TEST");
        new RelayCommand(param => this.ShowStartUpView());

I get the "app.cs does not contain a definition" on showstartupview, which is obvious, and I understand I could change this to MainWindowViewModel to get around this, but that would mean making everything in MainWindowViewModel static. Which is not good. What other options are there for me?

Apologies if this is a nooby question, I am new to C# and WPF and MVVM.

Upvotes: 0

Views: 1036

Answers (1)

MistyK
MistyK

Reputation: 6222

You should expose RelayCommand action to explicit method. And call that method in Window constructor. Instead of doing:

 new RelayCommand(param => this.ShowStartUpView());

Take method ShowStartUpView to your Window as a class member and your command either. Now in Window constructor invoke ShowStartUpView

public class Window
{
  InitializeComponent();
  ShowStartUpView();
}

And create command like this:

 new RelayCommand(ShowStartUpView);

I don't know why your command is in App instead of Window but you should move it.

Upvotes: 1

Related Questions