Avalonia样式选择器怎么用 Avalonia Style Selectors教程

来源:这里教程网 时间:2026-02-21 17:35:06 作者:

Avalonia 的样式选择器语法高度类比 CSS,用起来直观、灵活,核心就两步:先 选中控件,再 设置属性。不需要 TargetType 或 x:Key,靠 Selector 字符串就能精准定位。

基础类型与命名空间选择

最常用的是按控件类型匹配,比如让所有 Button 背景变蓝:

<style selector="Button"><Setter Property="Background" Value="Blue"/></style>
若控件在自定义命名空间(如
clr-namespace:MyApp.Controls
),需声明前缀并用竖线分隔:
xmlns:local="clr-namespace:MyApp.Controls"
,然后写
Selector="local|MyUserControl"
想连派生类(如 ToggleButton)也生效?用
:is(Button)
,它会匹配 Button 及所有继承自它的控件

按名称、类名和属性精准筛选

避免全局污染,常配合 Name 或 Classes 使用:

Name 选择器:给控件设
Name="saveBtn"
,样式写
Selector="Button#saveBtn"
Class 选择器:控件加
Classes="primary large"
,样式可写
Selector="Button.primary"
Selector="Button.primary.large"
(多个 class 同时满足)
属性值匹配:比如只对勾选的 CheckBox 生效:
Selector="CheckBox[IsChecked=True]"
;支持附加属性,如
Selector="TextBlock[(Grid.Column)=1]"

父子与后代关系选择

逻辑树结构决定匹配范围,注意符号差异:

子选择器(
>
):只匹配直接子级,例如
StackPanel > Button
不会选中嵌套在 Grid 里的 Button
后代选择器(空格):匹配任意层级后代,
StackPanel Button
会选中 StackPanel 下所有 Button,不管隔几层
组合使用更精细:比如
Window > DockPanel > Button.primary

模板内控件与伪类联动

很多视觉效果藏在控件模板里,必须用

/template/
显式进入:

改按钮内容区域圆角:
Selector="Button /template/ ContentPresenter"
+
CornerRadius
配合伪类实现交互态:
Button:pointerover /template/ ContentPresenter
表示鼠标悬停时才生效
常见伪类有:
:pressed
:disabled
:focus
:checked
,可叠加使用,如
CheckBox:checked /template/ Path

基本上就这些。写法简洁,但细节决定成败——比如命名空间要先 xmlns 声明、模板路径不能漏斜杠、伪类和后续选择器之间要留空格。多练几次,比写 CSS 还顺手。

相关推荐