前言
不同于WPF。Avalonia的样式是Styles。属于Windows.Styles。下面是用一段示例代码来快速入门 <Window.Styles>
<StyleInclude Source='/Styles/Button.axaml'/>
<StyleInclude Source='/Styles/TextBox.axaml'/>
<Style Selector="TextBlock.Label">
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#FF999999"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style Selector="TextBlock.ShowText">
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#FF333333"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="Margin" Value="8,0,15,0"/>
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
</Style>
</Window.Styles>
下面来分析整个代码
一、如何导入资源?
导入资源在需要的地方如Window.Styles、Application.Styles等这些地方导入。
通常写法为<StyleInclude>
的方式 如<StyleInclude Source='/Styles/Button.axaml'/>
即可导入资源文件。
二、如何使用Style
1定义Style
Style的设置和WPF类似,但是又有细微差别。WPF通常采用TargetType和key来确定和使用资源。上面代码Selector="TextBlock.ShowText"
中等效的WPF代码如下。
<Style TargetType="TextBlock" x:Key="Label">
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#FF999999"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
Avalonia使用Selector 的形式。
<Style Selector="TextBlock.Label">
<Setter Property="FontSize" Value="14"/>
<Setter Property="Foreground" Value="#FF999999"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
2.使用Style
代码如下(示例):
<TextBlock Classes="Label" Text="123"/>
使用Classes寻找定义的Selector
3.Style接入自定义控件
自定义控件采用<Style Selector="local|Button">
这种形式。下面定义一个CornerRadiusButton的圆角按钮。
样式写法如下
引入命名空间
xmlns:controls="clr-namespace:AvaloniaApplication1.Controls;assembly=AvaloniaApplication1"
简单样式
<Style Selector="controls|CornerRadiusButton.CorButton">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Right"/>
</Style>
详细样式(实现圆角按钮)
<Style Selector="controls|CornerRadiusButton.CorButton">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Right"/>
<Setter Property="Template">
<ControlTemplate>
<Border Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Background="{TemplateBinding Background}" CornerRadius="{TemplateBinding CornerRadius}">
<TextBlock Text="{TemplateBinding Content}"
Margin="{TemplateBinding Padding}"
Foreground="{TemplateBinding Foreground}"
FontSize="{TemplateBinding FontSize}"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter>
</Style>
关于Style的Avalonia触发器是通过伪类来实现的。下面一篇文章将详细介绍Avalonia的style的一些高级功能
参考Demo下载