当前位置: 欣欣网 > 码农

总结几种 Avalonia 项目里常见的 style 设置不生效故障

2024-02-13码农

在 Avalonia UI 中,样式( styles)类似于 CSS 样式,通常用于根据控件的内容或在应用程序中的用途对控件进行样式化;例如,创建用于标题文本块的样式。新手在开发过程中,经常会遇到编写好了样式代码,但界面上却没有生效的情况。这里列举了几种常见的情形,帮大家避坑。

1、通过属性设置的值会覆盖样式中的设置。

<TextBlockText="https://www.coderbusy.com"Background="Green"><TextBlock. styles>< styleSelector="TextBlock"><SetterProperty="Background"Value="Red"></Setter></ style></TextBlock. styles></TextBlock>

上述代码在 style 中将背景色设置为了红色,但因为外侧的 TextBlock 被单独设置了 Background 为绿色,因此 style 中的设置被覆盖并显示为绿色。

2、定义靠后的样式,会覆盖之前的设置。

<TextBlockText="https://www.coderbusy.com" classes="t1 t2"><TextBlock. styles>< styleSelector="TextBlock"><SetterProperty="Background"Value="Red"></Setter></ style>< styleSelector="TextBlock.t1"><SetterProperty="Background"Value="Green"></Setter></ style>< styleSelector="TextBlock.t2"><SetterProperty="Background"Value="Blue"></Setter></ style></TextBlock. styles></TextBlock>

因为 TextBlock.t2 的 定义 最靠后,所以背景呈现为蓝色。如果将 TextBlock.t2 的定义与 TextBlock.t1 对调,则背景将会呈现为绿色。

<TextBlockText="https://www.coderbusy.com" classes="t1 t2"><TextBlock. styles>< styleSelector="TextBlock"><SetterProperty="Background"Value="Red"></Setter></ style>< styleSelector="TextBlock.t2"><SetterProperty="Background"Value="Blue"></Setter></ style>< styleSelector="TextBlock.t1"><SetterProperty="Background"Value="Green"></Setter></ style></TextBlock. styles></TextBlock>

需要注意的是,本节所说的是「定义」的顺序,也就是 style 块在代码中的顺序,而不是 classes 属性中类名的顺序。笔者实测:改变 classes 中类名的顺序并不影响最终的呈现结果。

是「定义」的顺序,而不是「引用」的顺序。

3、在 UserControl 中为自身设置样式时,选择器应该使用实际类型,而不是 UserControl 。

如果想要在鼠标滑过时,将 UserControl 的背景改为绿色,可以使用下面的代码:

<UserControlxmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d"d:DesignWidth="800"d:DesignHeight="450"xmlns:local="clr-namespace:CoderBusy"x: class="CoderBusy.MyControl"><UserControl. styles>< styleSelector="local|MyControl"><SetterProperty="Background"Value="Transparent"></Setter></ style>< styleSelector="local|MyControl:pointerover"><SetterProperty="Background"Value="Green"></Setter></ style></UserControl. styles></UserControl>

需要注意的是,这里的选择器中目标对象必须是实际类型: local|MyControl ,而不能是 UserControl 。否则样式不会生效。