在 C# 中解析资源

发布于 2024-12-23 10:39:53 字数 254 浏览 5 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼藏柔 2024-12-30 10:39:53

我推荐资源概述

当您在 XAML 中使用 StaticResource 标记扩展时,它将沿着逻辑树向上搜索“somename”资源。您可以使用 FrameworkElement.FindResource (或 TryFindResource)方法在代码中执行相同的操作:

        myButton.Background = (Brush)this.FindResource("RainbowBrush");

当您使用 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:

        myButton.Background = (Brush)this.FindResource("RainbowBrush");

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文