Search code examples
c#wpfmodel-view-controller

How to setup a WPF project in MVC format?


I've been looking into better dividing up a WPF project. So far, this example has made the most sense to me (MVC style):

enter image description here Source: https://www.codemag.com/Article/1201061/CODE-Framework-Writing-MVVM-MVC-WPF-Applications

So I'm trying to figiure out best how to divvy up my project in this fasion. It seems that by default in WPF projects for each form a .xaml file is created, then a .cs file (controller?) is nested within it.

enter image description here

Questions:

  1. Is the .xaml file always going to be the 'view'?
  2. Is the .xaml.cs file always going to be the 'controller'?
  3. Since it doesn't appear a 'model' is created by default in the WPF structure, should my steps for setting up project structure be like this:
    a.) Separate the .xaml from it's .xaml.cs file.
    b.) Put the separated .xaml file in a Views folder
    c.) Put the separated .xaml.cs file in a Controllers folder
    d.) Create a Models folder
    e.) Create new class in Models folder that will be used by the .xaml.cs controller file we put in the controllers folder.

Does this seem accurate? I am trying to structure my code best for an interview, so I'd appreciate any advice.


Solution

  • Is the .xaml file always going to be the 'view'?'

    Yes.

    Is the .xaml.cs file always going to be the 'controller'?

    No. This is the code-behind file of the view. By default, it calls the compiler generated InitializeComponent() method to load the XAML markup that is defined in the .xaml file. Please see this thread for more information. The markup in .xaml and the code in .xaml.cs are partial classes of the same view. They belong together.

    a.) Separate the .xaml from it's .xaml.cs file.

    No. This makes no sense for the reason mentioned above.

    b.) Put the separated .xaml file in a Views folder

    You can put the views in a separate folder, but this includes the .xaml.cs files as well.

    c.) Put the separated .xaml.cs file in a Controllers folder

    No. There is no concept of "controllers" here.

    d.) Create a Models folder

    Sure.

    e.) Create new class in Models folder that will be used by the .xaml.cs file

    This is an option, but you would generally create a view model class that references the model and exposes properties that the view binds to. Please refer to this blog post for some basic introduction to the Model-View-ViewModel (MVVM) design pattern which is the recommended design pattern to use when developing XAML based UI applications. You will find a lot more information and examples if you Google or Bing for it.