Resource的应用

解释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就是新建的页面的名字。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值