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
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"
<Style TargetType="{x:Type local:DemoTextBox}">
<!-- create a trigger here -->

And a reference to the new control in the Window:
<Window x:Class="DepProp.Window2"
Title="Window2" Height="300" Width="300">
<ResourceDictionary Source="Generic.xaml"/>
<local:DemoTextBox x:Name="TextBoxV1" Text="Original Value" />

No comments: