2009-08-27 5 views
0

안녕하세요, WPF에서 RichTextBox을 사용하는 편집기를 개발 중입니다. 사용자가 선택할 수있는 글꼴을 구현할 수있는 기능을 구현해야합니다. 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

아름다운 대답 –