<Window x:Class="Example_04.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:Example_04"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<SolidColorBrush x:Key="MyBrush" Color="#05E0E9"/>
<Style TargetType="Border">
<Setter Property="Background" Value="#4E1A3D" />
<Setter Property="BorderThickness" Value="5" />
<Setter Property="BorderBrush">
<Setter.Value>
<LinearGradientBrush>
<GradientStop Offset="0.0" Color="#4E1A3D"/>
<GradientStop Offset="1.0" Color="Salmon"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="TextBlock" x:Key="lable">
<Setter Property="HorizontalAlignment" Value="Right"/>
<Setter Property="Foreground" Value="{StaticResource MyBrush}"/>
<Setter Property="FontFamily" Value="Arial"/>
</Style>
<sys:String x:Key="str">字符创定义</sys:String>
<sys:Double x:Key="number">100.973</sys:Double>
</Window.Resources>
<Border>
<StackPanel>
<TextBlock Style="{StaticResource lable}" Text="{StaticResource str}"></TextBlock>
<TextBlock HorizontalAlignment="Right" FontSize="36" Margin="20" Text="Title">
<TextBlock.Foreground>
<StaticResource ResourceKey="MyBrush"></StaticResource>
</TextBlock.Foreground>
<TextBlock.Width>
<StaticResource ResourceKey="number"></StaticResource>
</TextBlock.Width>
</TextBlock>
<Ellipse HorizontalAlignment="Center" Width="100" Height="100" Fill="{StaticResource MyBrush}" Margin="10" />
</StackPanel>
</Border>
</Window>
-
SolidColorBrush表示一把刷子,可以对控件进行绘制 -
两个Style样式器,Setter表示选择器,Property表示属性名称、Value表示属性值 -
一个字符串对象以及一个数字对象,需要引用如下命名空间 xmlns:sys="clr-namespace:System;assembly=mscorlib" -
第一种不指定键的两种写法 TargetType="Border"和TargetType="{x:Type Border}" 框架会将样式自动应用到目标对象 -
第二种需要指定键的两种写法 5.1 需要在控件中手动引用资源
使用资源
可以使用如下两种语法使用资源(参考上面代码已经覆盖这两种写法):
<!--第一种-->
<object property="{StaticResource key}" ... />
<!--第二种-->
<object>
<object.property>
<StaticResource ResourceKey="key" ... />
</object.property>
</object>
在这里引出两个概念: