我是一名有帮助的助手,可以为您翻译文本。
服务器端部分(片段):
我有一个自定义的无外观控件,派生自 Control 类。它的模板在 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">...
类别颜色.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。有什么想法让这些东西一起工作吗? 谢谢!
更新:如果我在控件的构造函数中添加以下行,则可行:
this.Resources = Application.LoadComponent(new Uri("PTE.Controls;Component/Resources/CategoriesColors.xaml", UriKind.Relative)) as ResourceDictionary;
但首先,它会复制字典(每次加载新字典),并且会消耗更多的内存。其次,我真的想在XAML中完成它。