通过代码隐藏在WPF访问资源 [英] Accessing a resource via codebehind in WPF
问题描述
我有如下我的窗口资源定义的自定义集合(在SketchFlow的应用程序,以便该窗口实际上是一个用户控件):
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>
我希望能够引用这个集合中的代码隐藏,我预计会是由X:名称,但我似乎无法访问它。
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.
我可以使用
myRef = (MyCollection) this.FindName("myKey");
但这似乎的hackish。这是不好的做法,什么会更好?谢谢。)
but this seems hackish. Is this bad practice, and what would be better? Thanks :)
推荐答案
您应该使用FindResource或TryFindResource
You should use FindResource or TryFindResource.
此外,一个好的做法是创建一个字符串常量将映射在资源字典的键的名称(这样就可以只在一个地方改变它)
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)
这篇关于通过代码隐藏在WPF访问资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!