Pukaai
Pukaai

Reputation: 377

WPF & MVVM, right way to do it

So I am doing my first WPF MVVM app. Just learning the right principle of MVVM, but there are some things that I don't understand ...

I already have several user controls defined. First question is what is better to use, UserControl or DataTemplates to change content of the MainWindow?

And how to make "Binding" in the "MainWindow.xaml" to change UserControl/DataTemplates when button is pressed? For example, When "next" button is pressed then contents of main window disappear and content of user control comes on the screen of "MainWindow.xaml". Maybe with "" binding, to disable it and enable it?

I found some example which function on DataTemplate A Simple MVVM Example. It helped me to implement some things, but I see some discussions over "UserControl" vs. "DataTemplate" and how to do it? So now I am confused :)

Upvotes: 0

Views: 446

Answers (1)

Jens Delannoy
Jens Delannoy

Reputation: 66

I recently made a WPF application with the MVVM pattern, and I did the following:

  • I have one 'Window', the mainwindow, and in this window all UserControls are loaded.

  • Every UserControl has a different Viewmodel, for examples a "GeneralSettingsUserControl" has a GeneralSettingsViewModel for validation and databinding.

  • Every UserControl has its own codebehind where data is bound to its ViewModel

  • The following code I found on the internet (I don't know the url anymore) but for me it did the trick to change de ContentControl in the mainwindow.

Switcher.cs:

public static mainWindow mainWindow;
public static void switchPage(UserControl p_objNewPage)
{
    mainWindow.navigate(p_objNewPage);
}

mainWindow.xaml.cs

public void navigate(UserControl nextPage)
{
     PageContent.Children.Clear();
     PageContent.Children.Add(nextPage);
     PageContent.LastChildFill = true;
}

PageContent is the name of the Grid where the main content is located. In every UserControl you can call the Switcher.switchPage(new UserControl) to change the content of the window. So when you click a button you can call this method.

Hope it helps and good luck.

Upvotes: 1

Related Questions