AppBarToggleButton
)和"继承"TargetType
?我想要实现的是将一个稍微定制的AppBarToggleButton(带有禁用的自动切换行为)放入CommandBar
中,并使其看起来完全像是常规的AppBarToggleButton
(即在给定的命令栏控件模板内接收为AppBarToggleButton
定义的任何样式)。他们说,DefaultStyleKey
应该有帮助,但它继承得很好,但是,唉,似乎没有参与本地样式解析/查找。
出于各种目的,我可能需要派生其他控件的子类,因此这里的最终目标是了解本地样式解析在内部如何工作,以及目标实例是否参与其中,或者它是否完全是外部过程。
一般来说,我们需要为自定义AppBarToggleButton
制作模板化控件。当我们用Visual Studio制作模板化控件时,它将在用于声明自定义控件样式的主题文件夹中生成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。