0

Using a generic base class control in WPF

Posted in C#, WPF at June 26th, 2009 by Gerrod / No Comments »

One thing that I find myself doing all the time is creating some type of base class for my windows/controls in WPF:


namespace Editors {
    public class EntityEditorControlBase<TModel> : UserControl
        where TModel : class, IEntityEditorModel {

        public TModel Model {
            get { return DataContext as TModel; }
            protected set { DataContext = value; }
        }
    }
}

Since this is a generic control you need to specify the concrete type arguments when you subclass it. You can do this in your WPF markup via the x:TypeArguments attribute:


<Editors:EntityEditorControlBase
    x:Class="ConcreteEntityEditorControl"
    x:TypeArguments="Models:ConcreteEntityEditorControlModel"
    xmlns:Editors="clr-namespace:Editors">

    <UserControl.Resources>
        <ResourceDictionary Source="../Resources/EditorResources.xaml" />
    </UserControl.Resources>

    <!-- control content here -->

</Editors:EntityEditorControlBase>

Two important things to note:

  • When you want to attach a resource dictionary to the class, you need to do so using the <UserControl.Resources> tag
  • In your base class control, make sure you include the [ContentProperty("Content")] and [DefaultProperty("Content")] tags on your class to avoid the horrible “The type ‘{0}’ does not support direct content” error.
Published in C#, WPF
Tags: ,

No Responses to “Using a generic base class control in WPF”

Leave a Reply