Accessing a resource via codebehind in WPF
You should use System.Windows.Controls.UserControl
's FindResource()
or TryFindResource()
methods.
Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).
You may also use this.Resources["mykey"]
. I guess that is not much better than your own suggestion.
Not exactly direct answer, but strongly related:
In case the resources are in a different file - for example ResourceDictionary.xaml
You can simply add x:Class
to it:
<ResourceDictionary x:Class="Namespace.NewClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>
And then use it in code behind:
var res = new Namespace.NewClassName();
var col = res["myKey"];