3
votes

I create some folder and organise my files to keep the MVVM Pattern clean. Model Folder, View Folder and ViewModel Folder.

It creates namespace problems, on many levels.

First the InitializeComponent();

  • does not exist in the current context

Second the StartupUri=

  • Can't find the ressources

I could find some answers but none were complete. From the basic situation:

  1. I create a new project WPF c# (Lets Name it PROJECT)
  2. I create 3 new folder.
  3. I move the MainView to the View folder.

What should be in PROJECT\app.xaml ?

  • x:Class=""
  • StartupUri=""

What should be in PROJECT\View\MainWindow.xaml ?

  • x:Class=""

What should be in PROJECT\View\MainWindow.xaml\MainWindow.cs ?

  • namespace

What about the PROJECT\ViewModel\FooViewModel.cs ?

What about the PROJECT\Model\FooModel.cs ?

And why ?

So furthe similar question could be completely anwsered. Thanks a lot

1
Don't move default files (MainWindow.xaml and App.xaml). Even though it's possible, it's generaly not recommanded as it gives more problems that it gives advantages...Atlasmaybe

1 Answers

5
votes

The App.xaml is the starting point of your application. x:Class should always define the full namespace of the actual class. so in your example, for the App.xaml is like below:

 x:Class="PROJECT.App"
 StartupUri="Viewmodel/MainWindow.xaml"

Startup uri defines a relative path to the desired first page. In your case would be Viewmodel/MainWindow.xaml.

If you move files from a location to another, you should check the namespace and adjust it accordingly. For your MainWindow would be like here:

using System.Windows;

namespace PROJECT.Viewmodel
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}
  • XAML
<Window x:Class="PROJECT.Viewmodel.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PROJECT"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

Keep in mind to set both the code behind (.cs) and the xaml file to point the same namespace. Wish you good luck!