我想创建一个扩展TextBox
的简单自定义控件。
我通过 Add -> New Item... -> Custom Control
创建它,然后对生成的代码进行一些更改。我将CustomControl
的基类更改为TextBox
,然后在Theme/Generic.xaml
文件中删除Template
设置器。
但是,当我将其添加到MainWindow
并运行时,它是空白的。这是我的最终代码:
文件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>
文件CustomControl.cs
:
namespace Test
{
public class CustomControl : TextBox
{
static CustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl), new FrameworkPropertyMetadata(typeof(CustomControl)));
}
}
}
中没有什么。它需要一个模板。
有两种方法可以做到这一点:首先,最简单,将Style
基于默认的TextBox
样式。这将为您提供默认模板和默认样式的其他所有内容。如果您愿意,请随意添加设定器,以覆盖继承的设定器。
<Style
TargetType="{x:Type local:MyCustomControl}"
BasedOn="{StaticResource {x:Type TextBox}}"
>
<Setter Property="BorderThickness" Value="10"/>
<Setter Property="BorderBrush" Value="Black"/>
</Style>
第二,写自己的模板。如果您发现需要执行默认模板不会为您做的任何事情,那么您将这样做。但是要当心,控制行为总是比您天真地假设要复杂得多。这些有时可能是深水。
以下是一些有关重新造成TextBox
或TextBox
的子类的文档。
您需要填写比这更多的属性,但这是一个开始:
<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>