wpf - 为什么在这种情况下无法解析 StaticResource?

标签 wpf xaml staticresource

我有一个异常(exception) “找不到名为‘mrg’的资源。资源名称区分大小写。” 当我尝试执行以下操作时:

主窗口.xaml:

<Window.Resources>
  <Thickness Left="0"
             Right="1"
             Bottom="2"
             Top="3"
             x:Key="mrg" />
</Window.Resources>
<Grid>
  <ItemsControl ItemsSource="{Binding}">
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <local:UserControl1 />
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>

主窗口.xaml.cs:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        List<string> source = new List<string>()
        {
            "item1",
            "item2",
            "item3",
            "item4",
            "item5",
        };
        DataContext = source;
    }
}

和 UserControl1.xaml:
<Grid>
    <TextBlock Text="{Binding}" Margin="{StaticResource mrg}" />
</Grid>

根据msdn article :

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

  • 因此,由于第 2 步,必须找到资源。但是,正如我在 Locals 中看到的那样捕获异常时的窗口,UserControl1.Parent == null .

    我对这个问题感到困惑。我可以解决的方法是将资源放到应用程序级别。

    我的问题是:为什么找不到 StaticResource ?

    最佳答案

    DataTemplate 形成了自己的逻辑树,它与 ItemsControl 的逻辑树是断开的。因此,遍历逻辑树的查找将找不到资源。

    我无法在 MSDN 中找到引用,只有 this article on CodeProject ,它写道:

    The elements that are part of an expanded template, hereafter referred to as "template elements", form their own logical tree which is disconnected from the logical tree of the object for which they were created.



    使用 DynamicResource而不是 StaticResource将克服这个问题。但是我不能确切地说出原因。也许可以在 Static and Dynamic Resources 中的静态资源查找行为和动态资源查找行为部分找到解释。 ,但我不确定。

    关于wpf - 为什么在这种情况下无法解析 StaticResource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14454672/

    相关文章:

    c# - 如何在 Entity Framework 6 中以编程方式为 MS SQL 创建连接字符串?

    c# - wp8 应用程序互联网连接检查并防止未处理的关闭

    xaml - UWP CommandBar 后退和前进按钮未显示

    c# - 在 Xamarin Forms 中居中对齐工具栏项目

    c# - 数据网格列标题按钮

    wpf - 将 <object property ="{StaticResource key}".../> 中的 Key 绑定(bind)到一个值

    wpf - 如何对组合框的 Observable 集合进行排序

    c# - 如何在不使用 MVVM 的情况下绑定(bind) DependencyProperty

    c# - 使用转换器绑定(bind)到静态资源

    reactjs - Spring 静态内容(css)未正确提供(spring boot)