Reputation: 3283
I'm currently working on a highlightable richtextbox control in WPF. The user can type some text into a search box and the richtextbox is highlighting the occurences of the searched word. Everything works fine until I have hyperlinks in the richtextbox, for example:
blablabla stackoverflow.com
And I search for the term:
st
It highlights the text ("st" in stackoverflow) correctly with a red foreground. But when I'm pressing a backspace - so the search term becomes the single "s" letter -, I get an exception:
System.ArgumentException: 'NamedObject' parameter type is not valid for formatting property 'Foreground'.
Parameter name: value
This is because my algorithm is looks like this:
Highlight the text in the richtextbox: I add every highlighted TextRange to a Dictionary, where the key is the highlighted TextRange, and the value is the old foreground property of that TextRange which I retrieve with this code:
textrange.GetPropertyValue(TextElement.ForegroundProperty)
Every time a user changes the filter string, I delete the old highlighting and I "re-highlight" the richtextbox with the new filter string like in Step 1.
The exception comes from the "delete the highlighting" part of the process. To delete the highlighting, I enumerate the Dictionary, and for every TextRange I reset the ForegroundProperty to the saved value:
foreach (var textRangeEntry in highlightedTexts)
{
textRangeEntry.Key.ApplyPropertyValue(TextElement.ForegroundProperty, textRangeEntry.Value);
}
The problem is that sometimes the saved ForegroundProperty becomes a DependencyProperty.UnsetValue - and I get an exception.
Which is strange. It looks like the ForegroundProperty "doesn't like" the UnsetValue, but for example, when I filter to
ov
in the text
blablabla stackoverflow.com
and then when I'm erasing the "v", everything's OK.
The exception only comes out when I'm highlighting the beginning of hyperlinks.
Is it a strange bug in WPF or I do something wrong?
Upvotes: 0
Views: 584
Reputation: 3283
I have realized that this problem (bug?) is inside the textrange.GetPropertyValue call. I will repost this question in a shorter and a more specific form.
Upvotes: 0