Skip to content

Creating a new UserControl

Grega Mohorko edited this page Dec 21, 2017 · 2 revisions

Follow the steps bellow after adding a new User Control (WPF) to your project.

Modifying the XAML file

  • Open up MyUserControl.xaml
  • Change the parent class to BaseControl:
    • Add a reference to the Controls namespace: xmlns:controls="clr-namespace:GM.WPF.Controls;assembly=GM.WPF"
    • Replace the opening tag <UserControl ... with <controls:BaseControl ...
  • [optional] If you have a ViewModel, add this attribute to the opening tag: d:DataContext="{d:DesignInstance Type=local:MyUserControlViewModel, IsDesignTimeCreatable=True}"

Your XAML file should look something like this:

<controls:BaseControl x:Class="MyWpfApplication.MyUserControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:controls="clr-namespace:GM.WPF.Controls;assembly=GM.WPF"
        mc:Ignorable="d"
        d:DesignHeight="300"
        d:DesignWidth="300"
        d:DataContext="{d:DesignInstance Type=local:MyUserControlViewModel, IsDesignTimeCreatable=True}"
        >
    <!-- The content -->
</controls:BaseControl>

Modifying the CodeBehind file

  • Open up MyUserControl.xaml.cs
  • Change the parent class to BaseControl

It should look something like this:

using GM.WPF.Controls;

namespace MyWpfApplication
{
    public partial class MyUserControl : BaseControl
    {
        public MyUserControl()
        {
            InitializeComponent();
        }
    }
}

If your control implements IDisposable and is placed in the BaseWindow, it will automatically be disposed when the window closes.

Clone this wiki locally