Reputation: 8292
I am experimenting with the WPF RichTextBox and notice that I can itterate through the blocks that make up its document by looping through RichTextBox.Document.Blocks.
What is the best way to get the Block that surrounds the caret?
I can get the CaretPosition and the ElementStart and ElementEnd properties of each block but can't see how to compare them because the actual character offsets are not exposed unless I am missing something obvious.
Upvotes: 3
Views: 5483
Reputation: 54
Paragraph currentParagraph = richTextBox1.CaretPosition.Paragraph;
This code will return a Paragaph object and instead of a Block object but because the blocks in a RichTextBox are typically paragraphs this will not pose any problem.
The Blocks property is the content property of RichTextBox. It is a collection of Paragraph elements.
Upvotes: -1
Reputation: 36
In Silverlight5 get the properties to be used to update a toolbar:
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);
}
Upvotes: 0
Reputation: 25
Answer above probably works in WPF RTB but not in Silverlight 4.0. Most likely SL doesn't allow access to the Document protion of the RTB. So you have to do it via Reflection....
Something like this:
Upvotes: 0
Reputation: 9386
var curCaret = richTextBox1.CaretPosition;
var curBlock = richTextBox1.Document.Blocks.Where(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
Upvotes: 8