【发布时间】:2012-01-03 20:01:48
【问题描述】:
如何更改 WPF RichTextBox 中当前选定文本区域的字体?
【问题讨论】:
标签: wpf richtextbox
如何更改 WPF RichTextBox 中当前选定文本区域的字体?
【问题讨论】:
标签: wpf richtextbox
我已经实现了一个可以更改字体大小、系列、颜色等的工具栏。我发现使用 wpf Richtextbox 的细节可能很棘手。设置选择字体是有道理的,但是,还有文本框的默认字体属性,以及当前的插入符号属性要与之抗衡。这是我为使其在大多数情况下使用字体大小而编写的内容。 fontfamily 和 fontcolor 的过程应该相同。希望对您有所帮助。
public static void SetFontSize(RichTextBox target, double value)
{
// Make sure we have a richtextbox.
if (target == null)
return;
// Make sure we have a selection. Should have one even if there is no text selected.
if (target.Selection != null)
{
// Check whether there is text selected or just sitting at cursor
if (target.Selection.IsEmpty)
{
// Check to see if we are at the start of the textbox and nothing has been added yet
if (target.Selection.Start.Paragraph == null)
{
// Add a new paragraph object to the richtextbox with the fontsize
Paragraph p = new Paragraph();
p.FontSize = value;
target.Document.Blocks.Add(p);
}
else
{
// Get current position of cursor
TextPointer curCaret = target.CaretPosition;
// Get the current block object that the cursor is in
Block curBlock = target.Document.Blocks.Where
(x => x.ContentStart.CompareTo(curCaret) == -1 && x.ContentEnd.CompareTo(curCaret) == 1).FirstOrDefault();
if (curBlock != null)
{
Paragraph curParagraph = curBlock as Paragraph;
// Create a new run object with the fontsize, and add it to the current block
Run newRun = new Run();
newRun.FontSize = value;
curParagraph.Inlines.Add(newRun);
// Reset the cursor into the new block.
// If we don't do this, the font size will default again when you start typing.
target.CaretPosition = newRun.ElementStart;
}
}
}
else // There is selected text, so change the fontsize of the selection
{
TextRange selectionTextRange = new TextRange(target.Selection.Start, target.Selection.End);
selectionTextRange.ApplyPropertyValue(TextElement.FontSizeProperty, value);
}
}
// Reset the focus onto the richtextbox after selecting the font in a toolbar etc
target.Focus();
}
【讨论】:
怎么样:
TextSelection text = richTextBox.Selection;
if (!text.IsEmpty)
{
text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);
}
【讨论】:
已解决...
if (this.TextEditor.Selection.IsEmpty)
this.TextEditor.CurrentFontFamily = SelectedFont;
else
this.TextEditor.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, SelectedFont);
【讨论】:
要获取当前选择,请使用:
Dim rng As TextRange = New TextRange(YourRtfBox.Selection.Start, YourRtfBox.Selection.End)
然后设置字体样式:
rng.ApplyPropertyValue(Inline.FontSizeProperty, YourFontSizeValue) rng.ApplyPropertyValue(Inline.FontFamilyProperty, YourFontFamilyValue)
【讨论】:
要更改 RichTextBox 中选择的字体系列,您应该使用以下命令:
text.ApplyPropertyValue(Run.FontFamilyProperty, value);
RichTextBox 中的选定文本是一个 Run 对象,因此必须使用 Run Dependency Properties。 这似乎至少在 Silverlight 中有效,所以在 WPF 中应该是一样的。
【讨论】: