简体   繁体   中英

WPF bug: TextRange.GetPropertyValue in RichTextBox

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM