WPF bug: TextRange.GetPropertyValue in RichTextBox

2019-09-01 04:14发布

问题:

I have to retrieve the Foreground property of the selected text in a WPF RichtTextBox, but I think, there is a bug in the TextRange.GetPropertyValue function. I've written a simple application to test the error:

   <RichTextBox x:Name="rtfBox">
        <RichTextBox.Document>
            <FlowDocument>
                <Paragraph>
                    <Run>run run run</Run>
                    <Hyperlink TargetName="http://stackoverflow.com">stackoverflow.com</Hyperlink>
                </Paragraph>
            </FlowDocument>
        </RichTextBox.Document>
    </RichTextBox>
    <Button Content="Click!" Height="28" Click="Button_Click" />

And in the code behind:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var textrange = new TextRange(rtfBox.Selection.Start, rtfBox.Selection.End);
        var propertyValue = textrange.GetPropertyValue(TextElement.ForegroundProperty);
        MessageBox.Show(propertyValue.ToString());
    }

When I select the first few characters of the stackoverflow hyperlink, the MessageBox says that the Foreground property is a DependencyProperty.UnsetValue, but when I select other parts of the link, it shows the true foreground color.

It looks like a bug.

Are there any workaround for this problem?

回答1:

It's because of the TextElement.ForegroundProperty. If you change it to Hyperlink.ForegroundProperty, it will show the true value.