gpt4 book ai didi

WPF RichTextBox : How to change selected text font?

转载 作者:行者123 更新时间:2023-12-05 00:24:19 24 4
gpt4 key购买 nike

如何更改 WPF RichTextBox 中当前选定文本区域的字体?

最佳答案

我已经实现了一个可以更改字体大小、系列、颜色等的工具栏。我发现 wpf 富文本框的细节可能很棘手。设置选择字体有一定的意义,但是,还有文本框的默认字体属性,以及需要处理的当前插入符属性。这是我为使其在大多数情况下使用字体大小而编写的内容。 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();
}

关于WPF RichTextBox : How to change selected text font?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com