Architect or Cobbler?
Good code starts with good design

Thick Pens .. or is that thick coders

Thursday, November 16, 2006

This morning on the train, I thought I'd add the Pen functionality to my application, and I immediately jumped in the deep end, but after a few minutes I started to get the feel that my code was getting distinctly whiffy.  I was adding all sorts of functionality to the Window that wasn't the window's responsibility, and I had to stop and refactor ... See this is a design blog after all :-)

I really needed to extract the Pen width and colour setting into it's own class.  So I decided to create a UserControl.  To do this is fairly straightforward, simply create a Xaml file that is either a UserControl or has a root element that is the control you want to subclass.  In my case I want an InkCanvas object, so I'm going to create the following Xaml

<InkCanvas x:Class="WPFScribble.ScribbleCanvas"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    
</InkCanvas>

This is pretty straightforward, it simply hooks up a code-behind file ScribbleCanvas, which must be a subclass of InkCanvas. It looks something like this:

public partial class ScribbleCanvas : InkCanvas
{
public ScribbleCanvas() { InitializeComponent(); }
}

The last thing to do is to change the Scribble.xaml to include our user control.  Since this is an XML file you have to use namespaces to define ownership, so you begin by defining a new namespace, in my case I decided to call it scribble, as follows

    xmlns:scribble="clr-namespace:WPFScribble"

Now you can replace references to the InkCanvas with references to your UserControl ScribbleCanvas like this

       <TabItem Header="Window1">
          <scribble:ScribbleCanvas>
            <scribble:ScribbleCanvas.DefaultDrawingAttributes>
              <DrawingAttributes  
                  Width="2" 
                  Height="2"/>
            </scribble:ScribbleCanvas.DefaultDrawingAttributes>
          </scribble:ScribbleCanvas>
       </TabItem>  

And if you run it there should be no difference in functionality.  Of course if I was doing the refactoring properly, there would be some tests to ensure the behaviour is identical, but I never claimed to be perfect.

So, a short little posting tonight, but I'm cream crackered.  Tomorrow I'll add the menus to do the pen width and colour settings.


# posted by James @ 9:05 PM   0 comments Comments: Post a Comment

<< Main blog page
This page is powered by Blogger. Isn't yours?