2013-12-12 79 views
1

我想直接綁定到我的Xaml中的RichTextBox的Blocks屬性。這是不可能的,因爲Blocks屬性是隻讀的。我可以直接綁定到一個單獨的運行:綁定到RichTextBox塊屬性

<RichTextBox x:Name="MyRichTextBox" FontSize="36" Margin="10" Foreground="White"> 
    <Paragraph> 
     <Run Text="{Binding MyObject.Text}" Foreground="Yellow"/> 
     <Run Text="{Binding MyObject.Text}" Foreground="Cyan"/> 
    </Paragraph> 
</RichTextBox> 

我想這樣做:

<RichTextBox x:Name="MyRichTextBox" Blocks="{Binding MyObject.RichTextBlocks}" FontSize="36" Margin="10" Foreground="White"/> 

特別,因爲我不知道提前多少塊將從綁定對象返回做。

是實現這一個RichTextBlocks屬性創建爲RichTextBox附加的行爲正確的方式是設定當枚舉通過塊,爲每一個來電RichTextBox.Blocks.Add()

我是C#,.NET和XAML的新手,所以請原諒基本問題,並簡單解釋的答案將不勝感激。

+0

有對此沒有開箱即用的解決方案 - 這樣從WP7任何解決方案是好去。檢查這個答案:http://stackoverflow.com/questions/12959137/bind-text-with-links-to-richtextbox – Nogard

回答

2

隨着@Nogard和其他職位的指針,我創建了我自己的類依賴屬性稱爲RichText。如果它對其他人有用,請在此發佈。

public class MyRichTextBox : RichTextBox 
    { 
     public static readonly DependencyProperty RichTextProperty = DependencyProperty.Register("RichText", typeof(Paragraph), typeof(MyRichTextBox), new PropertyMetadata(null, RichTextPropertyChanged)); 

     public Paragraph RichText 
     { 
      get 
      { 
       return (Paragraph)GetValue(RichTextProperty); 
      } 

      set 
      { 
       SetValue(RichTextProperty, value); 
      } 
     } 

     private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 
     { 
      MyRichTextBox richTextBox = (MyRichTextBox)dependencyObject; 
      Paragraph paragraph = (Paragraph)dependencyPropertyChangedEventArgs.NewValue; 

      // Remove any existing content from the text box 
      richTextBox.Blocks.Clear(); 

      // Add the paragraph to the text box 
      richTextBox.Blocks.Add(paragraph); 
     } 
    } 
} 

,並將此向我​​的XAML ...

<sub:MyRichTextBox x:Name="MyRichTextOverlay" RichText="{Binding CurrentOverlay.RichTextParagraph}" VerticalAlignment="Top" FontSize="36" Margin="10" Foreground="White" HorizontalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"/>