Custom control in WPF / Silverlight with XAML

14 11 2009

I’m currently working on a little side-project in WPF. A sort of imageviewer for imageboards. Since I want as much windowspace as possible for the images, I decided to put some of my icons on top of the image thumbnails. This proved hard to do. I therefore made a Custom Class called “MainImage”. This class will display both the original image (named here BackgroundImage) and two icons which I later added eventhandlers to to capture clicks. This worked out wonderfully well. The result is something like this:


First two normal images are put into my WrapPanel, then the third is my custom MainImage. Notice how it looks similar to the first two images but with the added icons on it. These icons are linked to two different event handlers in my codebehind. And thanks to my custom class, I can generate these custom images dynamically in my codebehind.

Tip: If you name your elements in a custom class (as I named my BackgroundImage ), you can set them and their properties in the codebehind just like any other property.

HowTo: To create a customclass, just rightclick your project in the Solution Explorer, choose “Add User Control” and choose a name for your control. You will now have a new item called YourName.xaml which in turn has a .cs file associated with it.

Here is the code I used for my MainImage control.

<UserControl x:Class="MyProject.MainImage"





            mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="200">




            <RowDefinition Height="2*" />

            <RowDefinition Height="1*" />



            <ColumnDefinition Width="*"/>

            <ColumnDefinition Width="*"/>

            <ColumnDefinition Width="*"/>


       <Image Name="BackgroundImage" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Grid.ColumnSpan="3" />

       <Image Name="ThreadImage" Source="Images/icon.png" Grid.Column="0" Grid.Row="1" Height="15" Width="15" />

       <Image Name="BrowserImage" Source="Images/icon.png" Grid.Column="1" Grid.Row="1" Height="15" Width="15" />






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: