2009-07-17 70 views
1

RichTextBoxのFontFamilyプロパティを使用すると、FlowDocument内のコンテンツ全体のFontFamilyが変更されます。 同じように、EditingCommands.ToggleBoldのようなコマンドを実行します。ここでは、キャレットの下の単語または書き込まれる新しいテキストのみが変更されます.FontsFamiliesとColorで同じことをする方法があるはずです。あなたがリッチテキストボックスの内側にRUNを使用したい前のテキストを変更せずにWPF RichTextBoxのFontFamilyを変更する方法

答えて

3
たぶん

ないneatestソリューションしかし、あなたはフォント

の一覧
public class CustomControl1 : RichTextBox 
    { 

public static readonly DependencyProperty CurrentFontFamilyProperty = 
       DependencyProperty.Register("CurrentFontFamily", typeof(FontFamily), typeof (CustomControl1), new FrameworkPropertyMetadata(new FontFamily("Tahoma"), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,new PropertyChangedCallback(OnCurrentFontChanged))); 
    } 

オーバーライドして、後でそれらをバインドすることができるように、独自のフォントプロパティを宣言し、リッチテキストボックスから継承し、いくつかの行動に

を追加することができますOnTextInput。あなたは、KeyDownイベントとkeyUpイベントのバブリングのために取り扱いを内蔵しており、あなたのCurrentFontPropertyキャレット位置を取得し、新しいを作成して変更された場合、それらの間のTextInputが

protected override void OnTextInput(TextCompositionEventArgs e) 
{ 
     if (fontchanged) 
     { 
      TextPointer tp = this.CaretPosition.GetInsertionPosition(LogicalDirection.Forward); 
      Run r = new Run(e.Text, tp); 
      r.FontFamily = CurrentFontFamily; 
      r.Foreground = CurrentForeground; 
      this.CaretPosition = r.ElementEnd; 
      fontchanged = false; 
     } 
     else 
      base.OnTextInput(e); 
    } 

を生成しているリッチテキストボックスに、このイベントをサブスクライブすることはできません新しいテキスト入力で実行し、FontFamily = CurrentFontFamilyを設定します。カレットが単語の上にある場合は、単語全体を変更することもできます。この記事は単語Navigate Words in RichTextBoxを見つけるのが面白いかもしれません。

1

、のようなもの:

<RichTextBox> 
    <Run FontFamily="Arial">My Arial Content</Run> 
    <Run FontFamily="Times" FontWeight="Bold">My bolded Times content</Run> 
    <Run>My Content that inherits Font From the RTB</Run> 
</RichTextBox> 

は[OK]を、これは、いくつかの低レベルの斗hickiesで遊ぶことを得ます。しかし、ここに行きます:

まず、ToggleButtonsとRichTextBoxをXAMLフォームに追加します。リッチテキストボックスでは、すべてのコマンドが一緒に機能することをシステムに知らせるために、コマンドバインディングをいくつか指定します。今

<RichTextBox Height="119" Name="RichTextBox1" Width="254" > 
     <RichTextBox.CommandBindings> 
      <CommandBinding Command="EditingCommands.ToggleBold" CanExecute="CommandBinding_CanExecute" ></CommandBinding> 
      <CommandBinding Command="EditingCommands.ToggleItalic" CanExecute="CommandBinding_CanExecute" ></CommandBinding> 
     </RichTextBox.CommandBindings> 
</RichTextBox> 
<ToggleButton MinWidth="40" Command="EditingCommands.ToggleBold" Height="23" HorizontalAlignment="Left" Name="Button1" VerticalAlignment="Top" Width="75" CommandTarget="{Binding ElementName=RichTextBox1}" >Bold</ToggleButton> 
<ToggleButton MinWidth="40" Command="EditingCommands.ToggleBold" Height="23" HorizontalAlignment="Left" Name="Button2" VerticalAlignment="Top" Width="75" CommandTarget="{Binding ElementName=RichTextBox1}" >Italics</ToggleButton> 

、リッチテキストボックスがありますし、2つのトグルボタン、およびトグルボタンが個別ToggleBold/ToggleItalicsにcommandbindingsに関連しているもの:

はここでXAMLです。 CODE側で

、私はこれらの2つの方法があります:ボタンが使用できるようにイベントハンドラを必要とするため、ボタンのクリックイベントハンドラがある

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)  
End Sub 

Private Sub CommandBinding_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs) 
    e.CanExecute = True 
End Sub 

を。

CanExecuteは、値が太字に使用できるかどうかを示します(たとえば、長さをチェックし、RTBが空の場合は太字にしないでください)。

本当に低レベルの制御が必要な場合は、RichTextFormatで処理する必要があります。詳細については、linkに従ってください。

+0

私はそれをdinamicallyに変更したいだけでなく、コマンドも変更します。これは静的テキストでは問題ありません。しかし、RichTextBoxのポイントは、キーボード入力によってさまざまなTextプロパティを持つテキストをdinamically生成します。 – jmayor

+0

次にRTFを調べ、それを読み書きします。 http://www.devcity.net/PrintArticle.aspx?ArticleID=356 –

+0

問題は、最初のとそれ以降のすべてが、それらのコンテナ(RichTextEditorの背後にあるFlowDocumentかもしれません)からtextElementプロパティを継承することです。エディタのフォントを変更すると、それを参照するすべての要素のフォントが変更されます。 これまでは、フォントを変更するときに新しい実行タグを生成することによってPreviewKeyをサブスクライブすることでそれを管理することができましたが、キーボード入力をフィルタリングする必要がありました。私はそれを行う良い方法があると確信しています。すべてのEditingCommnadsは、太字、イタリック、fontSizeで同じことをしています。もちろん、それは素晴らしい方法で行います。 – jmayor

2

ここでは、richtextboxのオーバーライドを避けるために使用しています。これにより、セレクションがある場合はそのセレクションのスタイルに変更したり、キャレットの後に「追加する」テキストのスタイルを変更することができます。それが役に立てば幸い。

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(); 
    } 
関連する問題