I have a custom collection defined in my window resources as follows (in a Sketchflow app so the window is actually a UserControl):
<UserControl.Resources>
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</UserControl.Resources>
I want to be able to refer to this collection in the codebehind, which I expected would be by the x:Name, but I can't seem to access it.
I can get a reference to it using
myRef = (MyCollection) this.FindName("myKey");
but this seems hackish. Is this bad practice, and what would be better? Thanks :)
You may also use
this.Resources["mykey"]
. I guess that is not much better than your own suggestion.You can use a resource key like this:
You should use
System.Windows.Controls.UserControl
'sFindResource()
orTryFindResource()
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).
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:And then use it in code behind:
If you want to access a resource from some other class (i.g. not a xaml codebehind), you can use
from
System.Windows
namespace.