通过 WPF 中的代码隐藏访问资源 [英] Accessing a resource via codebehind in WPF
问题描述
我在我的窗口资源中定义了一个自定义集合,如下所示(在 Sketchflow 应用程序中,因此该窗口实际上是一个 UserControl):
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:Name 引用,但我似乎无法访问它.
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");
但这似乎是骇人听闻的.这是不好的做法,什么会更好?谢谢:)
but this seems hackish. Is this bad practice, and what would be better? Thanks :)
推荐答案
你应该使用 System.Windows.Controls.UserControl
的 FindResource()
或 TryFindResource()
方法.
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).
这篇关于通过 WPF 中的代码隐藏访问资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!