wpf使用资源字典组织资源

如果希望在多个项目之间共享资源,可以创建一个资源字典。资源字典是一个存储希望使用的资源的XAML文档。下面是一个资源字典的示例,Dictionary1.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    >
    <sys:String x:Key="str3" >中国str3</sys:String>
</ResourceDictionary>

 

为了使用资源字典,需要将其合并到应用程序中某些位置的资源集合中。例如,可以放置到窗口的资源集合中,但是通常将其合并到应用程序的资源集合中,如下所示:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary1.xaml"></ResourceDictionary> 
                <ResourceDictionary Source="其它资源词典文件"></ResourceDictionary>
            </ResourceDictionary.MergedDictionaries>
            <sys:String x:Key="str2">中国str2</sys:String>
        </ResourceDictionary>
    </Window.Resources>

    <Grid>
        <Button Content="确定" Height="23" HorizontalAlignment="Left" Margin="119,142,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="159,67,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"  />
        <TextBox Height="23" HorizontalAlignment="Left" Margin="280,142,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
    </Grid>
</Window>

上面的标记通过显式地创建一个ResourceDictionary对象进行工作。资源集合总是ResourceDictionary对象,但是这只是为了显式指定细节从而可以设置ResourceDictionary. MergedDictionaries属性的一种情况(该属性通常为空)。

MergedDictionaries集合是一个ResourceDictionary对象的集合,可以使用该集合提供自己想要的资源集合。如果希望添加自己的资源,并合并到资源字典中,只需要在MergedProperties部分之前或之后放置您的资源就可以了。

 

后台访问资源:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBox2.Text = this.FindResource("str3").ToString();

        }

 

在前面介绍过,在不同但是相互重叠的资源集合中保存同名的资源是完全合理的。然而,合并使用相同资源名称的资源字典是不允许的。如果使用了相同的资源名称,当编译应用程序时就会收到一个XamlParseException异常。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值