[英]WPF RichTextBox - Selected Block?
我正在試驗 WPF RichTextBox,並注意到我可以通過循環 RichTextBox.Document.Blocks 來遍歷組成其文檔的塊。
獲取插入符號周圍的塊的最佳方法是什么?
我可以獲得每個塊的 CaretPosition 和 ElementStart 和 ElementEnd 屬性,但看不到如何比較它們,因為除非我遺漏了一些明顯的東西,否則不會公開實際的字符偏移量。
var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
在 Silverlight5 中獲取用於更新工具欄的屬性:
private void rtb_SelectionChanged(object sender, RoutedEventArgs e)
{
TextSelection ts = rtb.Selection;
object property;
property = ts.GetPropertyValue(Run.FontWeightProperty);
System.Windows.FontWeight fontWeight = property is System.Windows.FontWeight ? (FontWeight)property : FontWeights.Normal;
property = ts.GetPropertyValue(Run.FontStyleProperty);
System.Windows.FontStyle fontStyle = property is System.Windows.FontStyle ? (FontStyle)property : FontStyles.Normal;
TextDecorationCollection textDecorations = ts.GetPropertyValue(Run.TextDecorationsProperty) as TextDecorationCollection;
bool isUnderlined = textDecorations != null;
double? fontSize = ts.GetPropertyValue(Run.FontSizeProperty) as double?;
SolidColorBrush foreground = ts.GetPropertyValue(Run.ForegroundProperty) as SolidColorBrush;
Color foregroundColor = foreground != null ? foreground.Color : Colors.Black;
System.Diagnostics.Debug.WriteLine("fontweight:{0}, fontStyle:{1}, Underline:{2}, size:{3}, color:{4}",
fontWeight,
fontStyle,
isUnderlined,
fontSize,
foregroundColor);
if (fontSize.HasValue)
SetToolbarFontSize(fontSize.Value);
SetToolbarFontColor(foregroundColor);
}
上面的答案可能適用於 WPF RTB,但不適用於 Silverlight 4.0。 SL 很可能不允許訪問 RTB 的文檔部分。 所以你必須通過反射來做到這一點......
像這樣的東西:
Paragraph currentParagraph = richTextBox1.CaretPosition.Paragraph;
此代碼將返回 Paragaph 對象而不是 Block 對象,但由於 RichTextBox 中的塊通常是段落,因此不會造成任何問題。
Blocks 屬性是 RichTextBox 的內容屬性。 它是 Paragraph 元素的集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.