Reputation: 8338
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:
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.
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.
The following code, which throws a NullReferenceException
:
FlowDocument doc = (FlowDocument)FindResource("doc");
((Run)doc.FindName("run")).Text = "example text";
Upvotes: 3
Views: 1389
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