如何在控件内引用用户控件主机的静态资源? [英] How to refer to a User Control host's StaticResource inside the control?

查看:31
本文介绍了如何在控件内引用用户控件主机的静态资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Window.Resources

中有以下 StaticResource

<my:someobj x:Key="someResource"/>

我在窗口中有一个用户控件.我需要参考我的用户控件中的上述资源,我该怎么做?我无法将资源移动到单独的字典文件中.

<TextBlock Text="{Binding Source={StaticResource someResource}, Path=SomeText}"/>

上面给了我编译错误,没有找到someResource.我如何引用 someResource ?

解决方案

一旦您清楚资源查找行为,您就会得到答案.来自 MSDN,它是这样工作的:

<块引用>

  1. 查找过程在资源中检查请求的键由设置属性的元素定义的字典.
  2. 查找过程然后向上遍历逻辑树,到达父元素及其资源字典.这一直持续到根元素是到达.
  3. 接下来,检查应用程序资源.应用资源是资源字典中的那些资源由 WPF 应用程序的 Application 对象定义.

在您的情况下,window 不是 UserControl 的逻辑父级.因此,无法在那里找到资源.因此,您可以将应用程序资源下的资源移动,使其可用于您的 UserControl.

<my:someobj x:Key="someResource"/></Application.Resources>

I have the following StaticResource in my Window.Resources

<my:someobj x:Key="someResource" />

I have a user control inside window. I need to refer to the above resource inside of my user control, how can I do this ? I cannot move resource to a separate dictionary file.

<TextBlock Text="{Binding Source={StaticResource someResource}, Path=SomeText}" />

The above gives me compile error that someResource is not found. How can I refer to someResource ?

解决方案

You will get your answer once resource look up behavior is clear to you. From MSDN, it works like this:

  1. The lookup process checks for the requested key within the resource dictionary defined by the element that sets the property.
  2. The lookup process then traverses the logical tree upward, to the parent element and its resource dictionary. This continues until the root element is reached.
  3. Next, application resources are checked. Application resources are those resources within the resource dictionary that is defined by the Application object for your WPF application.

In your case window is not logical parent of UserControl. Hence, can't find the resource there. So, you can move the resource under application resources where it will be available for your UserControl.

<Application.Resources>
   <my:someobj x:Key="someResource" />
</Application.Resources>

这篇关于如何在控件内引用用户控件主机的静态资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆