jeff
jeff

Reputation: 8338

Accessing named element inside of window resources

Problem:

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>

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

What I've Tried So Far:

Upvotes: 3

Views: 1389

Answers (1)

Damith
Damith

Reputation: 63065

You can use LogicalTreeHelper.FindLogicalNode as

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

Remarks from above link:

  • 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.

Upvotes: 3

Related Questions