如何检测WPF RichTextBox中光标位置的当前文本格式?从WPF RichTextBox获取FontWeight/FontStyle/TextDecorations
3
A
回答
0
尝试以下其中RTB是RichTextBox的代码:
TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
3
我会使用,而不是选择开始和结束的CaretPosition,仿佛RichTextBox中实际上有一个选择跨越格式化你的多个区域会得到DependencyProperty.UnsetValue。
TextRange tr = new TextRange(rtb.CaretPosition, rtb.CaretPosition); object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
3
该主题的作者还询问了有关TextDecorations的情况,您未提供示例代码及其使用的不同。我张贴此作为进一步溶液:
var obj = _myText.GetPropertyValue(Inline.TextDecorationsProperty);
if (obj == DependencyProperty.UnsetValue)
IsTextUnderline = false;// mixed formatting
if (obj is TextDecorationCollection)
{
var objProper = obj as TextDecorationCollection;
if (objProper.Count > 0)
IsTextUnderline = true; // all underlined
else
IsTextUnderline = false; // nothing underlined
}
1
这里是确定fontWeight设置,FontStyle,TextDecorations(删除线和下划线)和的Super和下标中的溶液。
TextRange textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);
bool IsTextUnderline = false;
bool IsTextStrikethrough = false;
bool IsTextBold = false;
bool IsTextItalic = false;
bool IsSuperscript = false;
bool IsSubscript = false;
// determine underline property
if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Strikethrough))
IsTextStrikethrough = true; // all underlined
else if (textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline))
IsTextUnderline = true; // all strikethrough
// determine bold property
if (textRange.GetPropertyValue(Inline.FontWeightProperty).Equals(FontWeights.Bold))
IsTextBold = true; // all bold
// determine if superscript or subscript
if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Subscript))
IsSubscript = true; // all subscript
else if (textRange.GetPropertyValue(Inline.BaselineAlignmentProperty).Equals(BaselineAlignment.Superscript))
IsSuperscript = true; // all superscript
最困难的是没有回答看到我的答案! – msfanboy 2010-08-10 21:22:24