【发布时间】:2008-10-14 19:09:00
【问题描述】:
如何检测 WPF RichTextBox 中光标位置的当前文本格式?
【问题讨论】:
如何检测 WPF RichTextBox 中光标位置的当前文本格式?
【问题讨论】:
该主题的作者还询问了您未提供示例代码的 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
}
【讨论】:
我会使用 CaretPosition 而不是选择开始和结束,就好像 RichTextBox 实际上有一个跨越多个格式区域的选择,你会得到 DependencyProperty.UnsetValue。
TextRange tr = new TextRange(rtb.CaretPosition, rtb.CaretPosition); object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);【讨论】:
这是一个确定 FontWeight、FontStyle、TextDecorations(删除线、下划线)以及上标和下标的解决方案。
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
【讨论】:
试试下面的代码,其中 rtb 是 RichTextBox:
TextRange tr = new TextRange(rtb.Selection.Start, rtb.Selection.End);
object oFont = tr.GetPropertyValue(Run.FontFamilyProperty);
【讨论】: