Creating your own ContentControl in Silverlight

Unbelievable, but I had to spend half an hour to find out this.

If you want to create your own ContentControl in Silverlight (for example, your custom Image control displaying a mirror), you can do it as follows:

1) Create a class inheriting from ContentControl.

2) In its ctor, write the following:

           DefaultStyleKey = GetType();

3) Create the folder “Themes”, put the file generic.xaml there and insert the following content:

<ResourceDictionary
  xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”   
  xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml
  xmlns:local=”clr-namespace:<yourNamespace>
  >

    <Style TargetType=”local:<yourtype>“>
        <Setter Property=”Template”>
            <Setter.Value>
                <ControlTemplate TargetType=”local:<yourtype>“>
                    <Grid>                    
                        <ContentPresenter />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Now you can implement your control as usual, and it will get the XAML above as its ContentTemplate by default.

Leave a Reply

Categories

Archive