How to load RTF Text from database and display it in data template in a Datagrid? WPF C#

406 Views Asked by At

I'm trying to load RTF text from database and display it into datatemplate of custom RichTextBox . I would like to get the text with style , with code the matter is simple but when I'm trying to use <GridViewDataColumn.CellTemplate> <GridViewDataColumn.CellTemplate/> , it got difficult

  • Xaml code:

      <telerik:GridViewDataColumn DataMemberBinding="{Binding document}"  Width="*" x:Name="Description"  IsReadOnly="True">
                  <telerik:GridViewDataColumn.CellTemplate>
                      <DataTemplate >
                          <local:UC_Description  x:Name="richtext">
                          </local:UC_Description>
                      </DataTemplate>
                  </telerik:GridViewDataColumn.CellTemplate>
    
  • C# code:

          List= new Controller().GetAll();
    
          foreach (Model item in List)
          {
              RtfFormatProvider provider = new RtfFormatProvider();
              DocumentFormatProvidersManager.RegisterFormatProvider(provider);
              byte[] byteArray = Encoding.ASCII.GetBytes(item.Description);
              document = provider.Import(byteArray);
              FlowDocument flow = new FlowDocument();
    
          }
          GridViewList.ItemsSource = null;
          GridViewList.ItemsSource = List;         
    
    
          this.DataContext = this;
    
    
      }
    
      public RadDocument ImportXaml(string content)
      {
          RtfFormatProvider provider = new RtfFormatProvider();
          return provider.Import(text);
      }
      public string RtfToPlainText(string rtf)
      {
          byte[] byteArray = Encoding.ASCII.GetBytes(rtf);
          var flowDocument = new FlowDocument();
          TextRange tr;
          using (MemoryStream ms = new MemoryStream(byteArray))
          {
    
             tr = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
             tr.Load(ms, DataFormats.Rtf);
          }
    
          return tr.Text;
      }
    

How can I display text from RTF content in a data template?

1

There are 1 best solutions below

1
mm8 On

A template is a template and there is no UC_Description or RichTextBox until it has been applied at runtime.

What you could do is to handle the Loaded event for the UserControl and then set the Document property of the RichTextBox to your document:

XAML:

<telerik:GridViewDataColumn.CellTemplate>
    <DataTemplate >
        <local:UC_Description Loaded="OnLoaded" />
    </DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>

Code:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    UC_Description uc = (UC_Description)sender;
    uc.richTextBox.Document = ...;
}