如何从代码隐藏文件中的合并ResourceDictionary获取资源?

时间:2010-09-24 10:37:48

标签: c# .net wpf xaml resources

我有一个从Control类派生的自定义无外观控件。它的模板在Generic.xaml文件中定义。现在我想添加一些UI东西(主要是画笔),并希望在单独的资源字典中执行此操作,然后从代码隐藏的feil(* .xaml.cs)中访问这些内容。 见下文: Generic.xaml(片段):

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PTE.Controls" xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="PTE.Controls;component/Resources/CategoriesColors.xaml"/>
</ResourceDictionary.MergedDictionaries>
<CornerRadius x:Key="elementCornerBorder" BottomLeft="2" BottomRight="2" TopLeft="2" TopRight="2"/> 
<Style TargetType="{x:Type local:Element}">
    <Setter Property="Canvas.ZIndex" Value="50"/>
    <Setter Property="MinWidth" Value="60"/>
    <Setter Property="Template">...

CategoriesColors.xaml(片段):

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush StartPoint="0,1" EndPoint="1,0" x:Key="categoryNobleGas">
    <GradientStop Color="White" Offset="0"/>
    <GradientStop Color="RoyalBlue" Offset="0.5"/>
    <GradientStop Color="SteelBlue" Offset="1"/>
</LinearGradientBrush>...

服务器端部分(片段):

        private static void OnCategoryNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var categoryName = (CategoryName)e.NewValue;
        var element = (Element) d;
        switch (categoryName)
        {
            case CategoryName.NobleGas:
                element.Background = (Brush)element.TryFindResource("categoryNobleGas");
                break;
            case CategoryName.Halogen:
                element.Background = (Brush)element.TryFindResource("categoryHalogen");
                break;
            case CategoryName.OtherNonmetal:
                element.Background = (Brush)element.TryFindResource("categoryOtherNonmetal");
                break;
            case CategoryName.Metalloid:

它不起作用。基本上TryFindResource方法总是返回null。任何想法如何使这些东西一起工作? 谢谢!

UPD:如果我在控件的构造函数中添加以下行,它可以工作:

this.Resources = Application.LoadComponent(new Uri("PTE.Controls;Component/Resources/CategoriesColors.xaml", UriKind.Relative)) as ResourceDictionary;

但首先,它会复制字典(每次加载新字典)并消耗相当多的内存。其次,我真的想在XAML中做到这一点。

2 个答案:

答案 0 :(得分:0)

尝试在/内的ResourceDictionary中添加MergedDictionaries,如下所示。前面PTE

<ResourceDictionary Source="/PTE.Controls;component/Resources/CategoriesColors.xaml"/>

HTH

答案 1 :(得分:0)

你找到了答案吗?也许您可以通过在app.xaml的mergeddictionary中加载resourcedictionary来解决问题,并通过它访问它 Application.Current.TryFindResource(...)