← 返回所有博客文章

在Spread for ASP.NET中可以非常方便地在单元格中显示 RTF 内容,不过在Spread for Silverlight没有提供EncodeValue属性来解析 Spread for Silverlight 单元格内的 HTML 标签。

本文将讲解的也就是如何对单元格内的内容设置不同的样式,比如:您希望单元格内的部分文本显示为斜体,部分显示下划线,或者设置不同的字体颜色。为了实现以上功能,我们将在单元格中放置一个Silverlight RichTextBox在单元格中,因为RichTextBox可以显示不同的样式。

首先,我们需要创建一个自定义的绘图类,代码如下:

public class ControlDrawingObject : CustomDrawingObject
{
   private Control _rootElement;
   public ControlDrawingObject(int row, int col, Control control) : base(row, col) { _rootElement = control; this.ShowDrawingObjectOnly = true; }
   public override FrameworkElement RootElement
   {
      get { _rootElement.Margin = new Thickness(1); return _rootElement; }
   }
}

 

然后,我们需要创建一个使用该类型的 WorkSheet 类型,在自定义的WorkSheet类型中,我们将创建一个RichTextBox类的示例,并将传递给ControlDrawingObject,在本示例中我们设置了RichTextBox中的字体颜色,字体样式,和下划线样式:

public class MyWorksheet : Worksheet
{
   public bool DrawingObjectVisible { get; set; }
 
   public override DrawingObject[] GetDrawingObject(int row, int column, int rowCount, int columnCount)
   {
      //setting the rich text box for cell(1, 1)
      if (row != 1 || column != 1) return base.GetDrawingObject(row, column, rowCount, columnCount);
 
      RichTextBox rtb = new RichTextBox();
      rtb.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
      Paragraph prgParagraph = new Paragraph();
      Run rnMyText = new Run();
      rnMyText.Text = "This is some example text with ForeColor ";
      //setting the fore color for text
      rnMyText.Foreground = new SolidColorBrush(Colors.Brown);
      prgParagraph.Inlines.Add(rnMyText);
 
      Run rnMyText2 = new Run();
      rnMyText2.Text = "Italic Text ";
      //setting the font style to Italic
      rnMyText2.FontStyle = FontStyles.Italic;
      prgParagraph.Inlines.Add(rnMyText2);
 
      //write underlined text
      Underline unText = new Underline();
      unText.Inlines.Add(new Run() { Text = " This is some example text, underlined" });
      prgParagraph.Inlines.Add(unText);
 
      rtb.Blocks.Add(prgParagraph);
 
      DrawingObject dobj;
      dobj = new ControlDrawingObject(row, column, rtb);
      return new DrawingObject[] { dobj };
  }
}

 

运行效果:

源码下载:

VB.NET

TextStyleForCell_VB.zip (12.85 kb)

C#

TextStyleForCell_CSharp.zip (12.14 kb)