首页 > 解决方案 > UWP - 子类化内置控件并继承样式行为

问题描述

是否可以子类化控件(AppBarToggleButton在我的情况下)并“继承”TargetType基类?我想要实现的是有一个稍微定制的 AppBarToggleButton(具有禁用的自动切换行为)CommandBar并使其看起来完全像它是常规的(即接收为给定命令栏控件模板内部AppBarToggleButton定义的任何样式)。AppBarToggleButton他们说,DefaultStyleKey应该有所帮助,但它可以很好地继承,但是,唉,似乎没有参与本地样式解析/查找。

标签: c#xamluwpwindows-10-universal

解决方案


我可能出于各种目的需要对其他控件进行子类化,因此这里的最终目标是了解本地样式解析在内部是如何工作的,以及目标实例是否参与其中,或者它是一个完全外部的过程。

一般来说,我们需要为自定义制作模板控件AppBarToggleButton。当我们使用 Visual Studio 制作模板化控件时,它会Generic.xamlThemes文件夹中生成用于声明自定义控件样式的文件。自定义控件cs文件如下。

public sealed class CustomAppBarToggleButton : AppBarToggleButton
{
    public CustomAppBarToggleButton()
    {
        this.DefaultStyleKey = typeof(CustomAppBarToggleButton);
    }
}

如果您不想编辑默认样式,可以删除DefaultStyleKey用于将当前控件与 Generic.xaml 文件中的样式绑定的行。

打开Generic.xaml文件你会发现以下内容。它是空的风格。如果我们想做一些小的改动,你需要复制完整的AppBarToggleButton样式来替换它并编辑TargetTypelocal:CustomAppBarToggleButton. 然后您可以根据您的要求编辑样式。

<Style TargetType="local:CustomAppBarToggleButton" >
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:CustomAppBarToggleButton">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

如果你想创建一个新的依赖属性,请在cs文件中定义它,然后TemplateBinding在样式中使用绑定属性。有关更多信息,请查看此文档


推荐阅读