Setting styles for text with Spread for ASP.Net is really simple by using HTML tags with in a cell. However, there is no EncodeValue property for Spread for Silverlight to recognize these HTML tags with in a cell . Here I have come up with a work around which can be very useful if you want to format text with in a cell with different styles. For example you may want some part of the cell's text to be Italic and some part it be Underlined. You may also require to set different Forecolor for text with in a cell. This work around is going to be very useful in such scenarios. For this implementation, we are going to place a Silverlight RichTextBox in a cell which allows to format text with different style. First of all we will have to create a custom drawing object by inheriting CustomDrawingObject class.
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; }
}
}
Once we have this control, we will create a custom worksheet to use this control. In this custom worksheet we will create a RichTextBox object and pass this as a custom drawing object that we created above. We will make settings for RichTextBox as per our need. I have set ForeColor, FontStyle and UnderLine style for content in 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 };
}
}
The cell with the above settings looks as shown in the image below: Refer to the given samples for complete implementation. Download VB Sample Download C# Sample