从另一个ResourceDictionary引用一个资源

时间:2014-02-27 05:16:09

标签: c# wpf

例如,我们有两个ResourceDictionary

Global.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <FontFamily x:Key="GlobalFontFamily">Segoe UI</FontFamily>
</ResourceDictionary>

Part.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ReousrceDictionary Source="Global.xaml" />
    </ResourceDictionary.MergedDictionaries>
    <FontFamily x:Key="PartFontFamily">**Reference GlobalFontFamily here**</FontFamily>
</ResourceDictionary>

MainWindow.xaml

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ResourceDictionary.MergedDictionaries>
            <ReousrceDictionary Source="Part.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </Window.Resources>
    <Grid>
        <TextBlock FontFamily="{StaticResource PartFontFamily}" />
    </Grid>
</Window>

在某些视图中,我会使用PartFontFamily来设置元素字体系列。我想要实现的是,在设置PartFontFamily时使用指定的字体系列,否则请使用GlobalFontFamily。因此,我希望保留PartFontFamily密钥,并将其引用至GlobalFontFamily,因为客户没有PartFontFamily的指定字体系列。

有什么好的建议吗?

2 个答案:

答案 0 :(得分:0)

将Part.xaml合并到Global.xaml ...以便您可以引用Global.xaml中的所有内容......

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
     <ResourceDictionary.MergedDictionaries>
        <ReousrceDictionary Source="Part.xaml" />
    </ResourceDictionary.MergedDictionaries>
<FontFamily x:Key="GlobalFontFamily">Segoe UI</FontFamily>

将Global.xaml合并到您的MainWindow ...

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ReousrceDictionary Source="Global.xaml" />
    </ResourceDictionary.MergedDictionaries>
</Window.Resources>
<Grid>
    <TextBlock FontFamily="{DynamicResource PartFontFamily}" />
</Grid>
</Window>

您可以直接访问PartFontFamily此处...

答案 1 :(得分:0)

我想您想为您的资源制作 alias

<DynamicResource x:Key="PartFontFamily" ResourceKey="GlobalFontFamily"/>