2011-06-27 46 views
0

我需要将格式化文本数据绑定到RichTextBox。对于格式化,我似乎必须创建一系列具有特定格式的运行,然后将它们添加到段落中,并将其添加到RichTextBox上的blocks属性中。我试图绑定一个段落属性块,但它似乎不允许。段落没有项目源将其绑定到运行列表。我怎样才能将运行列表数据绑定到RichTextBox控件?数据绑定格式化文本到Silverlight中的richtextbox 4

谢谢

回答

0

这是我想出的解决方案。我创建了一个自定义的RichTextViewer类并从RichTextBox继承。

using System.Windows.Documents; 
using System.Windows.Markup; 
using System.Windows.Media; 

namespace System.Windows.Controls 
{ 
    public class RichTextViewer : RichTextBox 
    { 
     public const string RichTextPropertyName = "RichText"; 

     public static readonly DependencyProperty RichTextProperty = 
      DependencyProperty.Register(RichTextPropertyName, 
             typeof (string), 
             typeof (RichTextBox), 
             new PropertyMetadata(
              new PropertyChangedCallback 
               (RichTextPropertyChanged))); 

     public RichTextViewer() 
     { 
      IsReadOnly = true; 
      Background = new SolidColorBrush {Opacity = 0}; 
      BorderThickness = new Thickness(0); 
     } 

     public string RichText 
     { 
      get { return (string) GetValue(RichTextProperty); } 
      set { SetValue(RichTextProperty, value); } 
     } 

     private static void RichTextPropertyChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) 
     { 
      ((RichTextBox) dependencyObject).Blocks.Add(
       XamlReader.Load((string) dependencyPropertyChangedEventArgs.NewValue) as Paragraph); 

     } 
    } 
}