使用Findresource加载资源会引发异常 - WPF/C#

use*_*862 4 wpf resources

我正在WPF中编写CustomControl.我在我的Themes/Generic.xaml中有一些DataTemplates,在resourcedictionary级别,为它们分配了x:Key.

现在从相同的控件类代码中,我想找到并加载该资源,以便我可以动态地为代码中的某些东西做出贡献.

我试过base/this.FindResource("keyvalue"),this.Resources [""]等.

它一直返回找不到资源,因此为null.

该资源在generic.xaml中非常有用.

请帮忙.

Ale*_*x_P 7

回答有点迟,但可能会让其他人受益.

您尝试访问的资源位于主题级别,要从程序集中的任何位置访问它,必须由ComponentResourceKey标识:

<Style TargetType="{x:Type TreeViewItem}" 
       x:Key="{ComponentResourceKey {x:Type local:MyTVIStyleSelector}, tviBaseStyle}">
  <!-- style setters -->
</Style>
Run Code Online (Sandbox Code Playgroud)

然后在你的XAML中你会像这样引用它:

<Style TargetType="{x:Type TreeViewItem}" 
       x:Key="{ComponentResourceKey {x:Type local:MyTVIStyleSelector}, tviStyle_1}"
       BasedOn={StaticResource {ComponentResourceKey {x:Type local:MyTVIStyleSelector}, tviBaseStyle}}>
  <!-- style setters -->
</Style>
Run Code Online (Sandbox Code Playgroud)

并在你的代码中这样:

ComponentResourceKey key = new ComponentResourceKey(typeof(MyTVIStyleSelector), "tviStyle_1");
Style style = (Style)Application.Current.TryFindResource(key);
Run Code Online (Sandbox Code Playgroud)

还有一种冗长的XAML语法形式,看起来像这样(但它只是一样):

<Style TargetType="{x:Type TreeViewItem}" 
       x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyTVIStyleSelector}, ResourceId=tviBaseStyle}">
  <!-- style setters -->
</Style>
Run Code Online (Sandbox Code Playgroud)

请注意,即使必须设置TypeInTargetAssembly,它也不会限制对程序集中其他类型的此资源的访问.