Design pattern in WPF

.net, c#, mvvm, wpf

Solution

How do you go about separating the XAML out so that it isn't just a mash of everything in one file?

There are many ways, including creating a seperate `UserControl`, `CustomControl`, `Page` or `Window`

For example, if you wanted to pull some `XAML` out of your `MainWindow.xaml`, you could create a `UserControl` (right-click project, Add, New Item..., User Control (WPF)) called `MyUserControl.xaml` like this:

<UserControl x:Class="WpfApplication1.MyUserControl"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Grid>
        <TextBlock>This is from a different XAML file.</TextBlock>
    </Grid>
</UserControl>

and then use this control in your `MainWindow.xaml` like this:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:myControls="clr-namespace:WpfApplication1">
    <Grid>
        <myControls:MyUserControl/>
    </Grid>
</Window>

Note that you need to add a reference to the namespace of your `UserControl`

xmlns:myControls="clr-namespace:WpfApplication1"

Problem

I am making my first WPF application, so this question may seem rather odd. I have been reading about MVVM and so far it has made sense to me. What I don't understand, though, is separating all the XAML. What I mean is this: I assume you don't place everything in the MainWindow.xaml and just collapse controls based upon what is going to be used. I would think you would want a container that would contain xaml of other files. Is this correct? How do you go about separating the XAML out so that it isn't just a mash of everything in one file?

Original source

Related problems