Reputation: 122
I want to create a simple custom control that extends TextBox
.
I create it by Add -> New Item... -> Custom Control
and I make some change on the code generated automatically. I change the base class of the CustomControl
into TextBox
and delete the Template
setter in Theme/Generic.xaml
file.
But when I add it to MainWindow
and run, it is blank. Here is my final code:
File Theme/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:Test">
<Style TargetType="{x:Type local:CustomControl}">
<Setter Property="BorderThickness" Value="10"/>
</Style>
</ResourceDictionary>
File CustomControl.cs
:
namespace Test
{
public class CustomControl : TextBox
{
static CustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
}
}
}
Upvotes: 0
Views: 674
Reputation: 37059
There's nothing in it. It needs a template.
There are two ways to do that: First, easiest, base your Style
on the default TextBox
style. That'll give you the default template and everything else in the default style. Add setters at will to override the inherited ones, if you wish.
<Style
TargetType="{x:Type local:MyCustomControl}"
BasedOn="{StaticResource {x:Type TextBox}}"
>
<Setter Property="BorderThickness" Value="10"/>
<Setter Property="BorderBrush" Value="Black"/>
</Style>
Second, write your own template. If you find that you need to do anything that the default template won't do for you, you'll be doing it this way. But beware, control behavior always turns out to be much more complicated than you would naively assume. These can be deep waters at times.
Here's some documentation about retemplating a TextBox
or a subclass of a TextBox
.
You'll need to fill in a lot more properties than this, but here's a start:
<Style
TargetType="{x:Type local:MyCustomControl}"
BasedOn="{StaticResource {x:Type TextBox}}"
>
<Setter Property="BorderThickness" Value="10"/>
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl}">
<Border
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
>
<ScrollViewer Margin="0" x:Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Upvotes: 1