CPF 入門教程 - 樣式和動畫(三)
CPF NetCore跨平臺UI框架
系列教程
CPF 入門教程(一)
CPF 入門教程 - 資料繫結和命令繫結(二)
CPF 入門教程 - 樣式和動畫(三)
用樣式可以對內部元素進行批量設定屬性。
CPF裡採用CSS作為樣式描述。為什麼用css描述樣式?因為css結構簡單明瞭。
Xaml和CSS的簡單對比
<Style TagetType="Button"> <Setter Property="Background" value="Red"></Setter> ...... </Style>
等同於
Button{ Background:red; ...... }
css明顯比xaml簡潔
CPF中的css支援的選擇器
TextBlock { Foreground:rgb(255,0,0);} 選擇所有TextBlock型別的元素,型別不繼承判斷,比如自定義控制元件繼承Button,那樣式用Button的時候這個自定義控制元件不會應用該樣式
.test{Foreground:rgb(255,0,0);} 選擇所有包含test 類名的元素,類名通過Classes屬性新增
#test{Foreground:rgb(255,0,0);} 選擇所有Name屬性為test的元素
[IsMouseOver=true]{…} 新增觸發器
Button TextBlock{…} Button裡的後代為TextBlock的元素,
Button>TextBlock{…} Button直接子元素為TextBlock的元素,
自定義型別要支援css設定,需要實現string的隱式轉換,同時重寫ToString,使格式一致
public static implicit operator 自定義物件(string n) { return Parse(n);//自己寫字串解析和建立自定義物件 }
在窗體裡呼叫 LoadStyleFile("res://ConsoleApp1/Stylesheet1.css"); 載入樣式檔案,一般樣式檔案內嵌,內嵌檔案用res://開頭訪問
定義一個按鈕樣式
Button { BorderFill: #DCDFE6; IsAntiAlias: True; CornerRadius: 4,4,4,4; Background: #FFFFFF; } Button[IsMouseOver=true] { BorderFill: rgb(198,226,255); Background: rgb(236,245,255); Foreground: rgb(64,158,255); } Button[IsPressed=true] { BorderFill: rgb(58,142,230); }
執行效果
定義下拉框動態展開效果
@keyframes comboboxDropDown { 0% { RenderTransform: scale(1,0.1); } 100% { RenderTransform: scale(1,1); } } #DropDownPanel { RenderTransformOrigin: 50%,0; } #DropDownPopup[Visibility=Visible] #DropDownPanel { animation-name: comboboxDropDown; animation-duration: 0.1s; animation-iteration-count: 1; animation-fill-mode: forwards; }
css裡定義的動畫,暫時不支援緩動效果,比如加速,減速,回彈等等
C#裡使用動畫
RenderTransformOrigin = "100%,0"; RenderTransform = new GeneralTransform { ScaleX = 0.1f }; this.TransitionValue(a => a.RenderTransform, new GeneralTransform { ScaleX = 1 }, TimeSpan.FromSeconds(0.1f));
一般簡單的動畫直接使用TransitionValue方法就行,對某個屬性過渡到某個值
如果要做複雜的動畫,就需要用Storyboard,Timelines裡可以新增動畫播放流程,可以分成多段,流程值是0-1,意思就是這次的結束時間,開始是上一段的結束,最後一個必須是1,裡面可以加不同KeyFrames ,定義不同屬性的變換
var storyboard = new Storyboard { Timelines = { new Timeline(1) { KeyFrames = { new KeyFrame<SolidColorFill>{ Property=nameof(Control.Background), Value="0,0,0,100" } } } } }; } storyboard.Start(mask, TimeSpan.FromSeconds(0.3), 1, EndBehavior.Reservations);