WPF RichTextBox: как изменить выбранный текстовый шрифт?

как я могу изменить шрифт для текущей выбранной текстовой области внутри WPF RichTextBox?


person Néstor Sánchez A.    schedule 16.08.2010    source источник


Ответы (5)


Я реализовал панель инструментов, которая может изменять размер шрифта, семейство, цвет и т. д. Я обнаружил, что детали могут быть сложными с помощью богатого текстового поля 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();
    }
person littlekujo    schedule 16.11.2010

Как насчет чего-то вроде:

 TextSelection text = richTextBox.Selection; 
 if (!text.IsEmpty) 
 { 
     text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value); 
 }
person KrisTrip    schedule 16.08.2010
comment
По крайней мере, для размера шрифта. Вероятно, есть свойство для семейства шрифтов, если это то, что вы хотели изменить. - person KrisTrip; 17.08.2010
comment
Почти готово. Это работает для размера шрифта. Но для семейства шрифтов изменяется весь абзац, а не только выделение. - person Néstor Sánchez A.; 20.08.2010

Решено...

if (this.TextEditor.Selection.IsEmpty)
    this.TextEditor.CurrentFontFamily = SelectedFont;
else
    this.TextEditor.Selection.ApplyPropertyValue(TextElement.FontFamilyProperty, SelectedFont);
person Néstor Sánchez A.    schedule 03.01.2012
comment
Это решение основано на: stackoverflow.com/questions/1854703/ - person tgr42; 04.09.2015

Чтобы получить текущий выбор, используйте:

Dim rng As TextRange = New TextRange (YourRtfBox.Selection.Start, YourRtfBox.Selection.End)

Затем установите стиль шрифта:

rng.ApplyPropertyValue(Inline.FontSizeProperty, YourFontSizeValue) rng.ApplyPropertyValue(Inline.FontFamilyProperty, YourFontFamilyValue)

person JayGee    schedule 03.01.2012

Чтобы изменить семейство шрифтов для выделения в RichTextBox, вы должны использовать это:

text.ApplyPropertyValue(Run.FontFamilyProperty, value);

Выделенный текст в RichTextBox является объектом Run, поэтому необходимо использовать свойства зависимости Run. Кажется, это работает, по крайней мере, в Silverlight, то же самое должно быть и в WPF.

person nba bogdan    schedule 14.02.2011