在RichTextBox中设置字体属性

时间:2009-08-27 05:58:19

标签: wpf fonts wpf-controls richtextbox

HI, 我正在使用WPF中的RichTextBox开发一个编辑器,我必须实现一个功能,如果选择了某些文本,用户可以设置所选Text的字体,如果没有选择任何内容,则应为新文本设置字体。 如果我在以后的情况下设置RTB的字体属性(如FontStyleFontSize),它将设置整个文本的属性,如何设置新文本的字体属性(即,如果用户输入文本它将带有新的字体设置)。

1 个答案:

答案 0 :(得分:5)

我已经实现了一个可以改变字体大小,族,颜色等的工具栏。我发现使用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();
    }