我正在使用WPF RichTextBox处理文字处理器类型的应用程序。我使用的是SelectionChanged事件找出什么字体,字体粗细,风格等是使用下面的代码在RTB当前选择的:WPF RichTextBox SelectionChanged性能
private void richTextBox_SelectionChanged(object sender, RoutedEventArgs e)
{
TextSelection selection = richTextBox.Selection;
if (selection.GetPropertyValue(FontFamilyProperty) != DependencyProperty.UnsetValue)
{
//we have a single font in the selection
SelectionFontFamily = (FontFamily)selection.GetPropertyValue(FontFamilyProperty);
}
else
{
SelectionFontFamily = null;
}
if (selection.GetPropertyValue(FontWeightProperty) == DependencyProperty.UnsetValue)
{
SelectionIsBold = false;
}
else
{
SelectionIsBold = (FontWeights.Bold == ((FontWeight)selection.GetPropertyValue(FontWeightProperty)));
}
if (selection.GetPropertyValue(FontStyleProperty) == DependencyProperty.UnsetValue)
{
SelectionIsItalic = false;
}
else
{
SelectionIsItalic = (FontStyles.Italic == ((FontStyle)selection.GetPropertyValue(FontStyleProperty)));
}
if (selection.GetPropertyValue(Paragraph.TextAlignmentProperty) != DependencyProperty.UnsetValue)
{
SelectionIsLeftAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Left;
SelectionIsCenterAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Center;
SelectionIsRightAligned = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Right;
SelectionIsJustified = (TextAlignment)selection.GetPropertyValue(Paragraph.TextAlignmentProperty) == TextAlignment.Justify;
}
}
SelectionFontFamily,SelectionIsBold等分别是使用OneWayToSource的绑定模式托管UserControl上的DependencyProperty。它们绑定到一个ViewModel,而ViewModel又有一个绑定到它的视图,它具有字体组合框,粗体,斜体,下划线等控件。当RTB中的选择更改时,这些控件也会更新以反映选择的内容。这很好。
不幸的是,它的工作原理是牺牲了性能,在选择大量文本时会受到严重影响。选择一切显然很慢,然后使用Shift +箭头键来改变选择非常缓慢。太慢,无法接受。
我做错了什么?对于如何在RTB中将选定文本的属性反映到绑定控件而不会在此过程中杀死RTB的性能,有什么建议吗?
感谢你的代码,这确实提高了你所说的速度,但是当你在RTB中有大量文本时(比如说15页左右),它仍然很不稳定。如果突出显示所有文字并使用箭头键取消选择线条/文字,则它仍然滞后,非常明显。所以它更好,但仍然不存在。 可以这样的事情放在一个线程? – Scott 2010-08-19 20:43:55
我已经扩展了我的答案,让您了解进一步加速需要什么,以及线程是否会有所帮助。 – 2010-08-20 04:58:16
优秀的建议,谢谢雷。我会更详细地研究你的建议。 – Scott 2010-08-20 20:19:55