Xaml学习小结

Author Avatar
huuhghhgyg 3月 16, 2022
  • 在其它设备中阅读本文章

主要是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.xamlApplication.Resources里面添加定义
App.xaml中添加定义:

<Application.Resources>
    <!-- 在这里添加属性的定义 -->
</Application.Resources>

这样,样式就已经在整个App中定义了。

Resource Dictionary

Application.Resources中设定的Resource Dictionary(资源字典)可以用于设置

  • Resources
  • SolidColorBrush
  • Strings
  • Styles
  • StaticResource
  • Control Templates
  • Animation

不仅在PageApplication层面可以创建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}">
link
本文链接:
发文时间
3月 16, 2022
请遵循协议