我怎样才能成为私人'资源字典?

时间:2011-10-14 12:54:15

标签: c# wpf xaml dictionary

  

可能重复:
  How to make a Style that only exists within the context of a ResourceDictionary

我正在构建一个复杂的ResourceDictionary,它将公开我希望与包含该ResourceDictionary的项目共享的ControlTemplates。但是,此ResourceDictionary包含一系列支持的样式和模板,我不希望希望项目可用。我怎么能这样做?

例如:

<ResourceDictionary>
    <!-- Private dictionary items used to set up the publicly usable Omnibox templates -->
    <ResourceDictionary x:Key="PrivateDictionary">
        <Thickness x:Key="BaseValueMarginAdjustment">2,0,0,0</Thickness>            
        <!--Base Styles -->
        <Style x:Key="BaseElement" TargetType="FrameworkElement">...</Style>
        <Style x:Key="GridStyle" TargetType="Grid" BasedOn="{StaticResource BaseElement}">...</Style>
        <Style TargetType="Selector" x:Key="SelectorStyle" BasedOn="{StaticResource BaseElement}">...</Style>
        ...
    </ResourceDictionary>
    <!--Public CONTROL TEMPLATES -->
    <ControlTemplate TargetType="{x:Type local:OmniBox}"  x:Key="OBListBoxTemplate">
        <Grid x:Name="PART_Grid" Style="{StaticResource GridStyle}">
            <ListBox x:Name="PART_Value" Style="{StaticResource SelectorStyle}" />
            ...
    </ControlTemplate>
    <ControlTemplate ...>
    ...
</ResourceDictionary>

请注意,上述方法无效。特别是,上面编译,但有一个运行时错误,因为我希望公开显示的ControlTemplates无法找到上面的私有样式,如“GridStyle”。


尝试以下方面也没有成功:

    <ResourceDictionary>
        <!-- Private dictionary items used to set up the publicly usable Omnibox templates -->
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary>...</ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>

        <!--CONTROL TEMPLATES -->
        <ControlTemplate TargetType="{x:Type local:OmniBox}"  x:Key="OBTextBoxTemplate">
        ...

1 个答案:

答案 0 :(得分:1)

为什么不能将这些资源放在单独的资源字典中?因此,在您不希望看到这些资源的项目中,只需不要将它们合并在那里。

假设您在App.xaml中有这样的资源定义 -

<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/WpfApplication1;component/Themes/Dictionary1.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/WpfApplication1;component/Themes/Dictionary2.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

假设您的样式资源存在于Dictionary2.xaml中,只需从中省略第二个字典。

编辑:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="pack://application:,,,/WpfApplication1;component/Themes/Dictionary1.xaml"/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

您可以在ResourceDictionary2中添加ResourceDictionary1的引用。无论你想在哪里使用reosurces,如果你不想要全局引用,你可以随时添加ResourceDictionary1的引用。