Silverlight Custom Control – II : Properties
This is the second part of my serie about creating Custom Controls, if you missed the first, you should read it : Part I
In this Part, we’ll speak about Custom Control’s properties : How to databind a template property to an exposed property, and how to create new exposed properties.
The idea is to expose properties of your custom control to its users, as your custom control is inheriting another, its basically exposes the sames, in the previous article, we got
public class EditableTextBlock : Control
so our EditableTextBlock exposes Width, Height, Background …
But setting EditableTextBlock’s Background to Red does not affects the Grid’s Background Property (setted to AliceBlue) in the Template (generic.xaml), you can try it :
<ctrl:EditableTextBlock Background="Red"></ctrl:EditableTextBlock>
Download this code: Page.part.xaml
The control stay in AliceBlue …
At this point you can use some DataBinding to link the value of a property in your control template to the value of some exposed property of its parent, to do this, in generic.xaml, the Grid’s Background property must be Binded to the exposed Background Property :
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:Custom_Control_1"> <Style TargetType="controls:EditableTextBlock"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="controls:EditableTextBlock"> <Grid Background="{TemplateBinding Background}"> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary>
Download this code: generic.xaml
Now, the Grid’s Background is binded to the exposed Background !
How to create a new property ?
You have to use a DependencyProperty to expose your property :
Basically, a DependencyPorperty look like this :
// Replace [TYPE] with your property type // Replace [NAME] with your property name public [TYPE] [NAME] { get { return ([TYPE])GetValue([NAME]Property); } set { SetValue([NAME]Property, value); } } public static readonly DependencyProperty [NAME]Property = DependencyProperty.Register("[NAME]", typeof([TYPE]), typeof(EditableTextBlock), new PropertyMetadata([DEPEND ON THE TYPE]); // For more informations about PropertyMetadata and DependencyProperty // Read : http://msdn.microsoft.com/en-us/library/system.windows.dependencyproperty.aspx
Download this code: DependencyProperty.cs
So a Text Property looks like this :
public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(EditableTextBlock), new PropertyMetadata(string.Empty));
Download this code: TextProperty.cs
The EditableTextBlock control now exposes a Text property which can be Binded in your Template.