是否可以将控件(在我的情况下为AppBarToggleButton
)和基类的“继承” TargetType
子类化?我想要实现的是在CommandBar
中放入一个稍微自定义的AppBarToggleButton(具有禁用的自动切换行为),并使它看起来完全像是常规的AppBarToggleButton
(即,接收内部为AppBarToggleButton
定义的样式)给定的命令栏控制模板)。他们说,DefaultStyleKey
应该有帮助,但可以继承,但是,but,似乎不参与本地样式的解析/查找。
我可能出于各种目的需要将其他控件归类,所以这里的最终目标是了解局部样式解析如何在内部工作,并且目标实例确实参与其中,或者是一个完全外部的过程。
通常,我们需要为自定义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。