Win10系列:UWP界面布局基础5

(2)编写后台代码访问资源

下面通过一个例子来演示如何编写后台代码引用资源。新建一个Windows应用商店的空白应用程序项目,将其命名为AccessResourceApplication,打开项目下的MainPage.xaml文件,首先定义一个页面级别的按钮样式资源,键为ButtonStyle,在样式中设置按钮的文本颜色为红色,然后在Grid元素内添加一个按钮,设置按钮的名字为SampleButton,内容为"运行后启用样式",字体大小是20像素,并使用鼠标将控件拖动到合适的位置。界面设计的XAML代码如下所示:

<Page

x:Class="AccessResourceApplication.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="using:AccessResourceApplication"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d">

<Page.Resources>

<Style TargetType="Button" x:Key="ButtonStyle">

<Setter Property="Foreground" Value="Red"/>

</Style>

</Page.Resources>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Button Name="SampleButton" Content="运行后启用样式" FontSize="20" Margin="169,345,0,378"/>

</Grid>

</Page>

接下来,在MainPage构造方法中引用键为"ButtonStyle"的样式资源为SampleButton按钮设置样式,代码片段如下所示:

public MainPage()

{

this.InitializeComponent();

SampleButton.Style = (Style)this.Resources["ButtonStyle"];

}

由于引用的是当前页面中定义的资源,因此在上面代码中直接使用this对象的Resources属性,后面索引上资源的键ButtonStyle来访问该资源,并转换成Style类型赋值给SampleButton按钮的Style属性。

未调试时的效果如图3-6所示。启动调试,后台代码运行,查找键为"ButtonStyle"的样式资源并赋值给按钮的Style属性,使按钮的样式发生了变化,效果如图3-7所示。

图3-6 未运行时的效果 图3-7 启动调试得到的效果

3.资源重用

资源被定义之后,可以在多个对象中使用,就实现了资源重用。在XAML中,可重用的资源有以下几类:

  • 值类型,如字符串,这时重用的资源是该值的副本。
  • FrameworkElement.Resources属性元素或ResourceDictionary 元素内定义的资源,如样式、模板、动画等。
  • 某些类的内置共享资源,这些类有:Brush类的所有子类(包括 ImageBrush)和Transform 类的所有子类等。

下面通过一个简单的例子来演示如何进行资源重用。新建一个Windows应用商店的空白应用程序项目,并命名为ShareResourceApplication,双击打开MainPage.xaml文件,首先定义一个页面级别的画刷资源,键为SampleBrush,设置画刷的颜色为红色,然后在Grid元素内添加两个按钮,内容分别为"打开"和"关闭",这两个按钮的文本颜色都引用画刷的颜色。相应的XAML代码如下所示:

<Page

x:Class="ShareResourceApplication.MainPage"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="using:ShareResourceApplication"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

mc:Ignorable="d">

<Page.Resources>

<SolidColorBrush x:Key="SampleBrush" Color="Red"/>

</Page.Resources>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Button Margin="100" Content="打开" Foreground="{StaticResource SampleBrush}"/>

<Button Margin="200" Content="关闭" Foreground="{StaticResource SampleBrush}"/>

</Grid>

</Page>

在上面代码中,"打开"按钮和"关闭"按钮的Foreground属性都通过StaticResource标记扩展引用键为"SampleBrush"的资源,体现了资源一次定义,重复使用的特性。

启动调试,可以看到"打开"按钮和"关闭"按钮的文本颜色都为红色,效果如图3-8所示。

图3-8 资源重用的效果

原文地址:https://www.cnblogs.com/finehappy/p/6645724.html