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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With