我有一个从 Control 类派生的自定义 look-less 控件。它的模板在 Generic.xaml 文件中定义。现在我想向其中添加一些 UI 内容(主要是画笔),并希望在单独的资源字典中执行此操作,然后从代码隐藏文件 (*.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 来做。
最佳答案
尝试在 MergedDictionaries
内的 ResourceDictionary
中添加 /
,如下所示。 PTE
<ResourceDictionary Source="/PTE.Controls;component/Resources/CategoriesColors.xaml"/>
HTH
关于c# - 如何从代码隐藏文件中的合并 ResourceDictionary 获取资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3786206/