3

I'm using the following method to write text to my MainWindow. My question is, is there any way to change the Text of the FormattetText or the drawingvisual after it has been created? Or should I use another method to write my text, if I want it updated at runtime?

private Visual WriteText()
{   
   DrawingVisual drawingVisual = new DrawingVisual();
   using (DrawingContext drawingContext = drawingVisual.RenderOpen())
   {   
        FormattedText ft = new FormattedText("Hello world", CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Klavika"), 10, Brushes.Red);
        drawingContext.DrawText(ft, new Point(0, 0));
   }
   return drawingVisual;
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • You have to recreate the drawing visual again. – Rohit Vats Nov 24 '13 at 16:21
  • Is there no way around recreating it, it's something I will be doing all the time. while my program is running. –  Nov 24 '13 at 16:29
  • Drawing Visuals are rendered very fast. Recreating it won't affect your application. Just give it a try. – Rohit Vats Nov 24 '13 at 16:30
  • 1
    Do not confuse recreating and re-rendering. *Do not* create a new DrawingVisual each time the text changes. Just draw into an existing one, as shown in the answer given by Miky. – Clemens Nov 24 '13 at 16:43
  • @Clemens - Yeah my mistake. Meant re-rendering only. – Rohit Vats Nov 24 '13 at 16:45

1 Answers1

4

You can't change the text of a FormattedText object once it was created, but you can change the contents of the Visual object. If you have a reference to the DrawingVisual you want to change you could use something similar to your method:

 private Visual UpdateVisual(DrawingVisual drawingVisual, string updatedText)
 {
     using (DrawingContext drawingContext = drawingVisual.RenderOpen())
     {   
          FormattedText ft = new FormattedText(updatedText, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Klavika"), 10, Brushes.Red);
          drawingContext.DrawText(ft, new Point(0, 0));
     }
     return drawingVisual;
 }
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
  • 1
    Is it not Heavy duty memory waste, if done protected o methodverride void OnRender(DrawingContext dc) – Dr.Sai May 29 '20 at 08:51