我正在嘗試使用WPF RichTextBox,並注意到我可以循環遍歷通過RichTextBox.Document.Blocks循環構成其文檔的塊。WPF RichTextBox - 選定的塊?
什麼是最好的方式來獲得圍繞插入符號塊?
我可以得到每個塊的CaretPosition和ElementStart和ElementEnd屬性,但看不到如何比較它們,因爲實際的字符偏移不會暴露,除非我缺少明顯的東西。
我正在嘗試使用WPF RichTextBox,並注意到我可以循環遍歷通過RichTextBox.Document.Blocks循環構成其文檔的塊。WPF RichTextBox - 選定的塊?
什麼是最好的方式來獲得圍繞插入符號塊?
我可以得到每個塊的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();
上面的答案可能適用於WPF RTB,但不適用於Silverlight 4.0。 SL很可能不允許訪問RTB的文檔部分。所以,你必須通過反射做....
事情是這樣的:
謝謝。我不再使用WPF了。我終於意識到,有太多這樣的箍環可以跳過,所以我回到了WinForms ... – 2011-03-31 19:08:01
在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);
}
感謝馬特。正是我在找的東西。 – 2010-03-31 14:20:59