Creating your own ContentTemplates in WPF

This isn’t something that I do often, but rolling your own look-and-feel by starting a ContentTemplate from scratch can be a right pain in the botty. Today I found this excellent sample project from Microsoft, which contains custom ContentTemplates for most UI controls in the framework. It provides an excellent starting point for creating your own customized controls.

Check it out!

Posted in .Net, WPF at December 23rd, 2009. 1 Comment.

Using a generic base class control in WPF

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.
Posted in C#, WPF at June 26th, 2009. No Comments.

StaticResource vs DynamicResource

I’ve been focusing a lot (read: “learning”) on WPF lately, and one thing that crops up all the time is StaticResource and DynamicResource. I had tried to infer their usage/differences from the context of where I’d seen them used, but I could never quite get it right. Anyway, I just read a nice definition which makes it all rather clear:

Static resources are resolved at compile time, whereas dynamic resources are resolved at runtime.

Use DynamicResources when the value of the resource could change during the lifetime of the Application.

Use StaticResources when it’s clear that you don’t need your resource re-evaluated when fetching it – static resources perform better than dynamic resources.

Posted in .Net, WPF at June 17th, 2008. 5 Comments.

Quickduck logo