WPF:为ResourceDictionary提供一个名称

时间:2016-01-21 02:46:00

标签: c# wpf

我的图标中有一个完整的PathGeometry的ResourceDictionary,我是否可以给这个ResourceDictionary一个名字,这样我就可以使用一些C#来查看我的所有图标,只是为了让事情更加集中在一起?

所以我会使用其中一个PathGeometry,例如

App.Current.Resources.Icons["refresh1"] as Geometry

or

App.Current.Resources["Icons"]["refresh1"] as Geometry

目前我使用App.Current.Resources["refresh1"] as Geometry来使用其中一个PathGeometry。

编辑: 不清楚为什么这是,不清楚。下面的海报理解了这个问题,但我不清楚我想要这样做的原因。但是我的理由不是必需的,我只想回答我的问题,而不是讨论我为什么要这样做。

1 个答案:

答案 0 :(得分:2)

这是一个非常直截了当的问题,人们会花更多时间争论而不是回答! :)人们可以像他们喜欢的那样争论它的优点但是一旦你开始做动态加载ResourceDictionaries(比如说,来自外部插件DLL)这样的话题就会突然变得非常相关!

回答你的问题,是的,当然这是可能的。这里的主要警告是,如果您只是将ResourceDictionaries添加到您的应用程序资源字典中,那么XAML编译器会对您尝试执行的操作感到困惑。这里的技巧是明确指定一个顶级ResourceDictionary,然后添加所有资源,包括您的密钥&ResourceDictionaries,作为其内容:

<Application.Resources>

    <ResourceDictionary xmlns:sys="clr-namespace:System;assembly=mscorlib">

        <ResourceDictionary x:Key="Dictionary1">
            <sys:String x:Key="str1a">String 1A</sys:String>
            <sys:String x:Key="str1b">String 1B</sys:String>
            <sys:String x:Key="str1c">String 1C</sys:String>
        </ResourceDictionary>

        <ResourceDictionary x:Key="Dictionary2">
            <sys:String x:Key="str2a">String 2A</sys:String>
            <sys:String x:Key="str2b">String 2B</sys:String>
            <sys:String x:Key="str2c">String 2C</sys:String>
        </ResourceDictionary>

        <!-- All other application resources go here -->

    </ResourceDictionary>

</Application.Resources>

这里有一些XAML静态绑定到字典,表明此方法按预期工作:

<StackPanel>
    <ListBox ItemsSource="{StaticResource Dictionary1}" DisplayMemberPath="Value" />
    <ListBox ItemsSource="{StaticResource Dictionary2}" DisplayMemberPath="Value" />
</StackPanel>

结果:

enter image description here

如果要访问代码中的资源,则需要将第一个数组查找转换为ResourceDictionary,然后按实际项密钥对其进行索引:

var str = (App.Current.Resources["Dictionary1"] as ResourceDictionary)["str1a"].ToString();

如果这太乱了,那么你可以用一个像这样的助手类来清理它:

public class Global
{
    static Global _global = new Global();
    public static Global Dictionaries { get { return _global; } }

    public ResourceDictionary this[string index]
    {
        get { return App.Current.Resources[index] as ResourceDictionary; }
    }
}

然后你会像这样使用:

var str = (string)Global.Dictionaries["Dictionary1"]["str1a"];