在 C# 中解析资源
在 XAML 中,{StaticResource somename}
将从控件资源过渡到窗口资源,最后过渡到应用程序资源。在同一表单的代码隐藏中,Resources["somename"]
似乎仅对窗口资源进行操作。
我发现在窗口的代码隐藏中,为了解析在应用程序级别定义的资源,有必要显式引用 App.Current.Resources
。
我是否使用了错误的东西,或者这是预期的行为?
In XAML, {StaticResource somename}
will fall through from control resources to window resources, and finally application resources. In code behind for the same form, Resources["somename"]
appears only to operate on window resources.
I found that in a window's code-behind, in order to resolve a resource that is defined at the application level it is necessary to explicitly refer to App.Current.Resources
.
Am I using something incorrectly, or is this expected behaviour?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我推荐资源概述。
当您在 XAML 中使用 StaticResource 标记扩展时,它将沿着逻辑树向上搜索“somename”资源。您可以使用 FrameworkElement.FindResource (或 TryFindResource)方法在代码中执行相同的操作:
当您使用 someFrameworkElement.Resources["somename"] 时,您将直接访问该框架元素的资源字典,这与访问常规字典没有什么不同或哈希表对象——它没有任何智能来遍历逻辑树。
I'd recommend the Resources Overview.
When you use the StaticResource markup extension in XAML, it will walk up the logical tree, searching for the "somename" resource. You can do the same thing in code using the FrameworkElement.FindResource (or TryFindResource) method:
When you use someFrameworkElement.Resources["somename"], you are directly accessing that framework element's resource dictionary, which is no different than accessing a regular dictionary or hashtable object -- it doesn't have any smarts to traverse up the logical tree.