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

问题描述 投票:0回答:1

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

c# xaml uwp windows-10-universal
1个回答
0
投票

我可能出于各种目的需要将其他控件归类,所以这里的最终目标是了解局部样式解析如何在内部工作,并且目标实例确实参与其中,或者是一个完全外部的过程。

通常,我们需要为自定义AppBarToggleButton创建模板化控件。当我们使用Visual Studio制作模板控件时,它将在Themes文件夹中生成Generic.xaml文件,该文件用于声明自定义控件的样式。和自定义控件cs文件,如下所示。

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

如果您不想编辑默认样式,则可以删除用于将当前控件与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

© www.soinside.com 2019 - 2024. All rights reserved.