If you simply want to add behavior to an existing control you can inherit from that control, rather than create a whole new control from scratch. For example, let's say you want the text in a TextBox
control to automatically be selected when the control gains the focus, enabling the user to easily overwrite the existing text, instead of the default behavior in which the cursor is simply placed at the end of the existing text.
You have two main options you could use to achieve this behavior:
Using our example of a TextBox
that automatically selects all the text when it receives the focus, we can create a new class called CustomTextBox
inherit from TextBox
, and add the behavior:
public class CustomTextBox : TextBox
{
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
this.SelectAll();
}
}
By default, the new control (CustomTextBox
) will continue to use the default control template that the control it inherits from uses (TextBox
). So our CustomTextBox
control will continue to use the TextBox
's default control template. If you want to use a different default control template, simply assign the control's type to the DefaultStyleKey
property in its constructor, as shown in the following code:
DefaultStyleKey = typeof(CustomTextBox);
You then need to define a corresponding style resource containing the control template in the Generic.xaml
file, pointing both the style resource's TargetType
property and the control template's TargetType
property to the type assigned to the control's DefaultStyleKey
property, like so:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyControlLibrary">
<Style TargetType="local:CustomTextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:CustomTextBox">
<!-- Template goes here -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
The control will automatically look for a style resource defined in the Generic.xaml
file with a target type matching the type assigned to its DefaultStyleKey
property, and use that as its default control template.
Note A number of primitive controls don't appear in the Toolbox, but you might wish to inherit from them. These primitive controls form the base of many other controls. For example, the Selector
primitive control forms the base for the ListBox
and the ComboBox
controls. You will find these primitive controls in the System.Windows.Controls.Primitives
namespace with controls including ButtonBase
, Popup
, RangeBase
, RepeatButton
, ScrollBar
, Selector
, Thumb
, and ToggleButton
.