c# - UWP - 子类化内置控件并继承样式行为
问题描述
是否可以子类化控件(AppBarToggleButton
在我的情况下)并“继承”TargetType
基类?我想要实现的是有一个稍微定制的 AppBarToggleButton(具有禁用的自动切换行为)CommandBar
并使其看起来完全像它是常规的(即接收为给定命令栏控件模板内部AppBarToggleButton
定义的任何样式)。AppBarToggleButton
他们说,DefaultStyleKey
应该有所帮助,但它可以很好地继承,但是,唉,似乎没有参与本地样式解析/查找。
解决方案
我可能出于各种目的需要对其他控件进行子类化,因此这里的最终目标是了解本地样式解析在内部是如何工作的,以及目标实例是否参与其中,或者它是一个完全外部的过程。
一般来说,我们需要为自定义制作模板控件AppBarToggleButton
。当我们使用 Visual Studio 制作模板化控件时,它会Generic.xaml
在Themes文件夹中生成用于声明自定义控件样式的文件。自定义控件cs文件如下。
public sealed class CustomAppBarToggleButton : AppBarToggleButton
{
public CustomAppBarToggleButton()
{
this.DefaultStyleKey = typeof(CustomAppBarToggleButton);
}
}
如果您不想编辑默认样式,可以删除DefaultStyleKey
用于将当前控件与 Generic.xaml 文件中的样式绑定的行。
打开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
在样式中使用绑定属性。有关更多信息,请查看此文档。
推荐阅读
- css - MaterialUI TextField:更改背景颜色无法正常工作
- reactjs - 在不分配功能的情况下反应 Typescript FunctionalComponent
- apache-kafka - 为什么我在使用带有 EOS Beta 的 kafka 时丢失了消息
- python - Plotly:如何防止甘特图中条形的粗细不同?
- excel - 将数据与两个工作表进行比较并在 Excel VBA 中打印匹配的值
- python - 递归地将 int 转换为二进制 (Python)
- javascript - 使用 JavaScript 下载不工作 TamperMonkey
- java - 是否可以选择 JTextArea 的(多)行,类似于使用 JCombobox 的方式?
- system-verilog - Cross coverage inheriting iff clause of coverpoint
- java - 来自类字段/成员的 Spring SPEL 默认 @Value