2009-08-27 3 views
0

HI, Я разрабатываю редактор, используя RichTextBox в WPF, я должен реализовать функцию, которую пользователь может установить шрифт выбранного Text, если выбран какой-либо текст, если ничего не выбрано, то шрифт должен быть установлен для новый текст. Если я установил свойства шрифта (например, FontStyle, FontSize) RTB в более позднем случае, он установит свойства для всего текста. Как установить свойства шрифта для нового текста (т. Е. Если пользователь вводит текст, он будет иметь новую настройку шрифта).Установить свойства шрифта в RichTextBox

ответ

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(); 
    } 
+0

прекрасный ответ –

Смежные вопросы