Pages

Tuesday 18 November 2008

Custom Control Part 1

I've struggled to find a really simple example of creating a custom control. So I created a simple control that did only "one thing" then removed the "one thing" to leave just the very least plumbing that I could.

Starting with a new class that inherits from TextBox:
public class DemoTextBox : TextBox
{
static DemoTextBox()
{
// Create a callback for when the TextProperty changes
PropertyChangedCallback callback = new PropertyChangedCallback(TextPropertyChanged);
// Override the TextProperty metadata in order to link up the callback routine
TextProperty.OverrideMetadata(
typeof(DemoTextBox),
new FrameworkPropertyMetadata(callback));
}
static void TextPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
// Cast the Sender to an object of this class
DemoTextBox textBox = (DemoTextBox)sender;

}
}

Add a ResourceDictionary called Generic.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DepProp>
<Style TargetType="{x:Type local:DemoTextBox}">
<Style.Triggers>
<!-- create a trigger here -->
</Style.Triggers>
</Style>
</ResourceDictionary>

And a reference to the new control in the Window:
<Window x:Class="DepProp.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DepProp"
Title="Window2" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary Source="Generic.xaml"/>
</Window.Resources>
<StackPanel>
<local:DemoTextBox x:Name="TextBoxV1" Text="Original Value" />
</StackPanel>
</Window>

No comments: