Search code examples
c#wpfdrawingcontextformatted-textdrawingvisual

Changing the text of a FormattedText


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;
}

Solution

  • 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;
     }