WPF自定义控件是空白的



我想创建一个扩展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>

第二,写自己的模板。如果您发现需要执行默认模板不会为您做的任何事情,那么您将这样做。但是要当心,控制行为总是比您天真地假设要复杂得多。这些有时可能是深水。

以下是一些有关重新造成TextBoxTextBox的子类的文档。

您需要填写比这更多的属性,但这是一个开始:

<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>

最新更新