将WPF本地资源转换为应用程序资源

时间:2012-05-02 09:19:52

标签: c# .net wpf c#-4.0

我在XAML中有一个本地资源,我希望它可以被代码的其他部分使用。如何使其成为“全局”(即应用程序范围的资源)?这是我的本地资源:

<ResourceDictionary >
   <local:BoolToLightConvertor x:Key="LightConverter" / >
</ResourceDictionary>

如何将其放入App.xaml?

2 个答案:

答案 0 :(得分:1)

应用程序资源 除了在元素或窗口级别定义资源外,您还可以定义 特定应用程序中的所有对象都可以访问的资源。您可以创建一个应用程序 打开App.xaml文件(对于C#项目)或Application.xaml文件 (对于Visual Basic项目)并将资源添加到Application.Resources集合中,如 如下所示:

<Application x:Class="WpfApplication.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="Window1.xaml">
   <Application.Resources>
      <SolidColorBrush x:Key="appBrush" Color="LightConverter" />
   </Application.Resources>
</Application>

答案 1 :(得分:0)

按如下方式创建文件(例如SharedResources.xaml):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Your.Namespace.Here;assembly=Your.Assembly.Here">
    < local:BoolToLightConvertor x:Key="LightConverter" / >
</ResourceDictionary>

在App.xaml中添加以下行:

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="SharedResources.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style TargetType="{x:Type Rectangle}" />
        </ResourceDictionary>
    </Application.Resources>

您现在可以在XAML中使用此转换器

<Style TargetType="{x:Type Rectangle}"/>是一种解决方法,可以阻止WPF错误忽略您的资源字典,并在此处提出了另一个问题的建议。但是,链接很遗憾我现在不知道了)