访问窗口资源内的命名元素 [英] Accessing named element inside of window resources

查看:34
本文介绍了访问窗口资源内的命名元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我正在尝试访问在窗口资源中定义的 FlowDocument 中的命名 Run 元素.为了澄清我的意思,请考虑以下代码:

I'm trying to access a named Run element within a FlowDocument which is defined in the Window Resources. To clarify what I mean, consider the follow code:

<Window.Resources>
    <FlowDocument x:Key="doc">
        <Paragraph>
            <Run x:Name="run" />
        </Paragraph>
    </FlowDocument>
</Window.Resources>

在这里,我将尝试访问名为run"的 Run 元素.

Here, I'd be trying to access the Run element named "run."

到目前为止我尝试过的:

  • 只需使用元素的名称即可访问它.但是,窗口资源中的命名元素显然没有与窗口内容中定义的元素相同的默认可访问性,因为这种方法不起作用.

  • Simply using the element's name to access it. However, named elements in the window's resources apparently don't have the same default accessibility as elements defined in the window's content, because this method did not work.

尝试向 Run 元素添加一个键,然后通过 FindResource() 方法访问该元素.不幸的是,似乎无法将键添加到嵌套元素中.

Attempting to add a key to the Run element and then accessing the element through the FindResource() method. Unfortunately, it seems that keys cannot be added to nested elements.

下面的代码,抛出一个NullReferenceException:

The following code, which throws a NullReferenceException:

FlowDocument doc = (FlowDocument)FindResource("doc");
((Run)doc.FindName("run")).Text = "example text";

推荐答案

您可以使用 LogicalTreeHelper.FindLogicalNode as

You can use LogicalTreeHelper.FindLogicalNode as

 var doc = this.Resources["doc"] as FlowDocument;
 ((Run)LogicalTreeHelper.FindLogicalNode(doc, "run")).Text = "example text";

以上链接的评论:

  • FindLogicalNode 的搜索方向是朝向子对象(树下);FindName 方法的搜索方向是朝向父对象(沿着树向上).
  • FindName 方法受 XAML 名称范围的概念控制.使用 FindName 可以保证只有一个对象该名称存在,因为 XAML 名称范围强制唯一性.在相比之下,FindLogicalNode 忽略 XAML 名称范围并且可能跨越 XAML搜索期间的名称范围边界.
  • The search direction for FindLogicalNode is toward child objects (down the tree); the search direction for the FindName methods is towards parent objects (up the tree).
  • The FindName methods are governed by the concept of a XAML namescope. Using FindName you are guaranteed that only one object of that name exists, because XAML namescopes enforce uniqueness. In contrast, FindLogicalNode ignores XAML namescope and might cross XAML namescope boundaries during the search.

这篇关于访问窗口资源内的命名元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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