UWP-对内置控件进行子类化并继承样式行为子类、控件、样式、行为

2023-09-04 02:28:20 作者:当个烂人

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

推荐答案

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

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

public sealed class CustomAppBarToggleButton : AppBarToggleButton
{
    public CustomAppBarToggleButton()
    {
        this.DefaultStyleKey = typeof(CustomAppBarToggleButton);
    }
}
pb数据窗口控件怎么实现双击选中一行, 并且 该行要变颜色,接下

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

打开Generic.xaml文件,您将看到以下内容。这是一种空洞的风格。如果我们想做一些小的更改,您需要复制完整的AppBarToggleButton样式来替换它,并将TargetType编辑为local: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在样式中绑定该属性。有关更多信息,请查看此document。