在 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 。否則樣式不會生效。