Xaml学习小结
主要是Xaml的“绑定”和“资源”
Xaml静态资源绑定
需要绑定一个resource的时候,需要的表达式就是大括号里面有“StaticResource”,再加上resource的名字。这种绑定只在App运行的时候进行一次,因为是静态资源,所以它就不会变了。
如:
<TextBlock Foreground = "{StaticResource MyBrush}" />
StaticResource
表明了我们所绑定的资源的类型
单个属性的绑定
可以创建单个属性的资源绑定,如:
<Page.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Brown"/>
</Page.Resources>
<!-- 使用 -->
<TextBlock Text="Hello World" Foreground="{StaticResource MyBrush}"/>
还可以创建值绑定,如将Slider
的值绑定到ProgessBar
中:
<ProgressBar Maximum="100" Value="{x:Bind MySlider.Value, Mode=OneWay}">
多个属性的绑定(Style)
也可以创建多个值类型的绑定,如设置背景、字体、字号等属性,如:
<Page.Resources>
<Style TargetType="Button" x:Key="MyButtonStyle">
<!-- 定义了目标类型、样式(资源)名称 -->
<!-- 下面是各个属性值的设置 -->
<Setter Property="Background" Value="Blue"/>
<Setter Property="FontFamily" Value="Arial Black"/>
<Setter Property="FontSize" Value="36"/>
</Style>
</Page.Resources>
<Button Content="My Button Style Example"
Height="100"
Style="{StaticResource MyButtonStyle}" />
<!-- 资源的名称是“MyButtonStyle” -->
属性的继承
使用BasedOn
属性
如HeaderTextBlockStyle
就是继承自BaseTextBlockStyle
原文引用:
<Style x:Key="HeaderTextBlockStyle" TargetType="TextBlock" BasedOn="{StaticResource BaseTextBlockStyle}">
...
</Style>
跨页引用资源
如果要跨页引用属性定义,需要在App.xaml
的Application.Resources
里面添加定义
在App.xaml
中添加定义:
<Application.Resources>
<!-- 在这里添加属性的定义 -->
</Application.Resources>
这样,样式就已经在整个App中定义了。
Resource Dictionary
在Application.Resources
中设定的Resource Dictionary(资源字典)可以用于设置
- Resources
- SolidColorBrush
- Strings
- Styles
- StaticResource
- Control Templates
- Animation
- …
不仅在Page
和Application
层面可以创建Resource Dictionary,还可以创建名为Merged Resource Dictionary
,用于在多个文件中定义Resource Dictionary,以此降低程序的复杂性,并允许在不同的项目中重复使用Dictionary文档。
比如,在项目中创建一个Dictionary1.xaml
文件(ResourceDictionary
类型),内容如下:
<ResourceDictionary
xmlns=""
...>
<x:String x:Key="greeting">Hello World</x:String>
<ResourceDictionary/>
在其它文件中的引用(以Page
为例):
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- 可以合并多个Dictionary入这个文件,只需要向里面添加 -->
<ResourceDicitonary Source="Dictionary1.xaml">
<ResourceDictionary.MergedDictionaries/>
<ResourceDictionary/>
<Page.Resources/>
使用系统已经构建好的主题
可以直接在Style="{StaticResource ...}"
里面根据IntelliSense查找,或者在控件的属性框内,找到Miscellaneous中的Style
,选中System Resource
,进行选择。
Xaml非静态资源绑定
ThemeResource
ThemeResource
和系统主题有关,使用系统主题中的颜色:
<!-- 使用系统的主题色 -->
<Rectangle Fill="{ThemeResource SystemAccentColor}">
<!-- 使用系统的窗口颜色(亮/暗等) -->
<Rectangle Fill="{ThemeResource SystemColorWindowColor}">