WPF bug: TextRange.GetPropertyValue in RichTextBox

亡梦爱人 提交于 2020-01-06 14:48:35

问题


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.



来源:https://stackoverflow.com/questions/11668598/wpf-bug-textrange-getpropertyvalue-in-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!