c#-访问窗口资源内部的命名元素

问题:

我正在尝试在Window资源中定义的FlowDocument中访问一个命名的Run元素.为了阐明我的意思,请考虑以下代码:

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

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

到目前为止我尝试过的内容:

>只需使用元素名称即可访问它.但是,窗口资源中的命名元素显然不具有与窗口内容中定义的元素相同的默认可访问性,因为此方法无效.
>尝试将键添加到Run元素,然后通过FindResource()方法访问该元素.不幸的是,似乎不能将键添加到嵌套元素中.
>以下代码引发NullReferenceException:

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

解决方法:

您可以使用LogicalTreeHelper.FindLogicalNode作为

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

来自以上链接的评论:

  • 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.
上一篇:CodeGo.net>如何外部分配事件处理程序的用户控件内的控件?


下一篇:c#-关闭并清理ViewModel中的视图