Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a resource with Findresource throws exception - WPF/C#

Tags:

resources

wpf

I am writing a CustomControl in WPF. I have some DataTemplates in my Themes/Generic.xaml, at the resourcedictionary level, with x:Key assigned for them.

Now from within the same control class code, i want to find and load that resource so i can dynamically assing to something in the code.

I have tried base/this.FindResource("keyvalue"), this.Resources[""] etc.

It keeps returning that the resource is not found and hence null.

The resource is defenitely there in the generic.xaml.

Please help.

like image 292
user61862 Avatar asked Dec 10 '22 22:12

user61862


1 Answers

A bit late for an answer, but it might benefit the others.

The resource you're trying to access is at the theme level, to access it from anywhere in your assembly it must be identified by ComponentResourceKey:

<Style TargetType="{x:Type TreeViewItem}" 
       x:Key="{ComponentResourceKey {x:Type local:MyTVIStyleSelector}, tviBaseStyle}">
  <!-- style setters -->
</Style>

then in your XAML you'd reference it like this:

<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>

and in your code like this:

ComponentResourceKey key = new ComponentResourceKey(typeof(MyTVIStyleSelector), "tviStyle_1");
Style style = (Style)Application.Current.TryFindResource(key);

There is also a verbose form of XAML syntax that looks like this (but its just the same thing):

<Style TargetType="{x:Type TreeViewItem}" 
       x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyTVIStyleSelector}, ResourceId=tviBaseStyle}">
  <!-- style setters -->
</Style>

Note that even though the TypeInTargetAssembly must be set it does not restrict access to this resource for other types in assembly.

like image 58
Alex_P Avatar answered Apr 02 '23 15:04

Alex_P