Separation of Concerns Using Code Files

Few WPF applications will take the 100% code or 100% XAML approach as you have seen thus far. In
reality, a ‘middle of the road’ approach is recommended.

Similar to an ASP.NET web application, WPF allows you to have a C# (or VB) file that works in conjunction
with a related XAML file. The XAML file is only concerned with
UI descriptions defined via markup. The
code file is concerned with
programming logic.

Elements defined in XAML can be accessed in the code file and vice versa if required. To do so, you should
assign a
Name property to the XAML element.

Here is the simple WPF application yet again, this time making use of code files. As a naming convention,
code files have
-xaml- embedded within the file name. However, this is not required. Recall from your
previous lab that the auto-generated
*.g.cs / *.g.vb file completes your partial class definition. The
InitializeComponent() method is defined within an auto-generated *.g.cs / *.g.vb file.


// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;

namespace SimpleXamlApp
{
public partial class MainWindow : Window
{
  public MainWindow()
  {
    // This method is defined
    // within the generated MainWindow.g.cs file.
    InitializeComponent();
  }

  private void btnExitApp_Clicked(object sender, RoutedEventArgs e)
  {
    // Get a handle to the current application and shut it down.
    Application.Current.Shutdown();
  }
}
}



The Application definition could also make use of the code-file approach. The XAML file would still contain
the
StartupUri property setting and so on.


// MyApp.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;

namespace SimpleXamlApp
{
public partial class MyApp : Application
{
  private void AppExit(object sender, ExitEventArgs e)
  {
    MessageBox.Show("App has exited");
  }
}
}


The code-file approach is the default behavior of Visual Studio WPF apps. When you select the WPF project
template from the File | New Project menu, you are given an
Application-derived type and initial Window-
derived type. Each type is composed of a *.cs / *.vb file, *.xaml file, and the auto-generated *.g* file.
Collectively, these three partial class definitions provide complete functionality.
Separation of Concerns Using Code Files
Table of Contents
Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used exclusively as an
online learning aid.  Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services