解释Resource
Resource是资源的意思,也就是可以把一些我们要用到的固定的风格写在里面,避免重复代码。
比如我们设计一个按钮的风格,它的颜色,它的字体,它的各种风格。只要是出现在我设计的程序中的按钮都要是一种风格的,我们可以在Resource里面统一设定,直接拿来用就好了,修改也只是修改Resource里面的风格。
Resource在页面中使用
可以放在一个页面里面的<Page>
标签下,设定风格。
<Page.Resource>
<SolidColorBrush x:Key="MyBrush" Color="Brown"/>
<x:String x:Key="greeting">Hello World</x:String>
<Style TargetType="Button" x:Key="MyButtonStyle">
<Setter Property="Background" Value="Blue"/>
<Setter Property="FontFamily" Value="Arial Black"/>
<Setter Property="FontSize" Value="36"/>
</Style>
</Page.Resource>
设定完风格后的使用。
<TextBlock Text="{StaticResource greeting}" Foreground="{StaticResource Brush}"/>
<Button Content="My Button Style Example"
Height="100"
Style="{StaticResource MyButtonStyle}"/>
这样的风格只有在本页面有效,不是全局有效的。
Resource全局有效
Resource想要全局有效,就要在App.xaml中设定。
<Application.Resource>
<SolidColorBrush x:Key="MyBrush" Color="Brown"/>
<x:String x:Key="greeting">Hello World</x:String>
<Style TargetType="Button" x:Key="MyButtonStyle">
<Setter Property="Background" Value="Blue"/>
<Setter Property="FontFamily" Value="Arial Black"/>
<Setter Property="FontSize" Value="36"/>
</Style>
</Application.Resource>
还可以新建立一个叫做资源字典的页面,也可以创建Resource。写完风格之后要在使用界面写下如下代码。
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"/>
<ResourceDictionary Source="Dictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
Dictionary1.xaml和Dictionary2.xaml就是新建的页面的名字。