wpf - 如何在控件内引用用户控件主机的 StaticResource?

标签 wpf xaml

我的 Window.Resources 中有以下 StaticResource

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

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

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

上面给出了未找到 someResource 的编译错误。我如何引用 someResource

最佳答案

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

  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.

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

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

关于wpf - 如何在控件内引用用户控件主机的 StaticResource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465747/

相关文章:

c# - 为 Windows 应用商店中的 Combobox SelectedItem 实现双向绑定(bind)

c# - WP8 照片相机源,旋转 Video rush 时被拉伸(stretch)

c# - Windows 8 XAML Metro App 中的基本 UserControl 类

c# - 如何使用异步命令 MVVM WPF

c# - WPF MVVM 数据模型

.net - 使用 MVVM 处理 WPF 中的对话框

c# - 在 WPF 中的两个用户控件之间发送命令

c# - DataGrid 的选定项

.net - WPF打印以适合页面

wpf - 资源字典中的资源未得到应用