2010-09-24 49 views
3

我有一個從Control類派生的自定義無標頭控件。它的模板在Generic.xaml文件中定義。現在我想添加一些UI的東西(主要是刷子),並希望在單獨的資源字典中做到這一點,然後從代碼隱藏代碼(* .xaml.cs)中訪問這些東西。 參見波紋管: Generic.xaml(片段):如何從代碼隱藏文件中的合併ResourceDictionary中獲取資源?

<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中做到這一點。

回答

0

嘗試在MergedDictionaries之內的ResourceDictionary中加入/,如下所示。的PTE

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

HTH

+0

Nope :(沒有幫助:( – 2010-09-24 16:11:28

0

盈方你有沒有找到答案?也許你可以通過加載你的app.xaml的mergeddictionary中的resourcedictionary並通過 Application.Current.TryFindResource(...)

相關問題