This is a mirror of official site: http://jasper-net.blogspot.com/

My Experiences in Silverlight 4 : Writing re-usable Controls

| Thursday, April 7, 2011
These days I am working on Silverlight and creating Custom controls which would be re-usable in another projects. And when you set out to write re-usable Silverlight controls, Silverlight toolkit is the best code to look up to.

When you download the Silverlight toolkit. The toolkit installer also copies source code of the toolkit at           “%Program Files%\Microsoft SDKs\Silverlight\v4.0\Toolkit\Apr10\Source” folder. When you start exploring the source code, you will notice a peculiar way the source code for toolkit is arranged. Every control in toolkit is written as a content control and has a resource dictionary that has a default style.

So, inspired by this style of writing custom controls, I set out. Now the reason why you want write a custom control is you require certain custom fields and a custom style and behaviors. So when you define these controls and the style, you also want your custom properties to appear in your style(Or else why would you define those additional controls. Typically your style for your control would look something like this.

and the your custom control would look something like this.

  xmlns:vsm="clr-namespace:System.Windows;assembly=System.Windows"
  xmlns:layoutPrimitivesToolkit="clr-namespace:System.Windows.Controls.Primitives"
  xmlns:layoutToolkit="clr-namespace:System.Windows.Controls">

  <Style TargetType="my:CustomControl1">
    <Setter Property="Foreground" Value="#FF000000" />
    <Setter Property="BorderBrush" Value="#FFEAEAEA"/>
    <Setter Property="HorizontalAlignment" Value="Left" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="my:CustomControl1">
          <Grid x:Name="Root">
            <vsm:VisualStateManager.VisualStateGroups/>
            <Border
               x:Name="Border"
               BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" Background="{TemplateBinding Background}"
               BorderBrush="{TemplateBinding BorderBrush}">
<TextBlock Text={TemplateBinding MyCustomProperty1}
              </Border>
          </Grid>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ResourceDictionary>

Read more: Windows Phone 7

Posted via email from Jasper-net

0 comments: