How do draw FormattedText (if not in the onRender method)

I draw some Ellipse and add them to a Grid.

Then I'd like to add some FormattedText to each Ellipse. This i could do by getting the RectangleBounds of the Ellipse.

But following this example:

I need a DrawingContext to draw the text. But if I don't wantto override onRender, how can I get a DrawingContext?


You can use a DrawingGroup instead. It has an Open method that returns a DrawingContext and you can use that to construct a drawing.

You'll then need to arrange for that drawing to appear in the UI somehow. The easiest way is to wrap it in a DrawingBrush and use that to paint some existing element in the UI. For example, if you've got an ellipse called myEllipse, this will set its Fill property to be a DrawingBrush based on a DrawingGroup that contains a single bit of FormattedText:

var drawing = new DrawingGroup();
using (var context = drawing.Open())
    var text = new FormattedText("This is some text",
        new Typeface("Calibri"),
    context.DrawText(text, new Point(0, 0));

var db = new DrawingBrush(drawing);
db.Stretch = Stretch.None;
myEllipse.Fill = db;

If you've already filled the Ellipse with something else, you have two choices. You could either add more content to this drawing - you can make as many calls into the context as you like. For example, if I add this immediately before the call to context.DrawText:

context.DrawRectangle(Brushes.Cyan, null, new Rect(0, 0, 300, 100));

I'll get a cyan background behind the text. (You'd need to adjust the coordinates in these examples to suit your layout, of course.)

But it's probably simpler to add an extra element to host the drawing, rather than trying to piggy-back it into an element that's there to do something else. So you could put a Rectangle element positioned directly over the Ellipse, and use a DrawingBrush such as this as the Fill for that Rectangle. The Rectangle won't actually look rectangular, because this DrawingBrush doesn't paint in its whole area. So the effect will look much the same as it would if you'd layered a TextBlock over an Ellipse.

Need Your Help

When I try unwrapping a var, I get an error

ios swift wrapper forced-unwrapping

I'm trying to create a var without assigning a value when it's initialized. I'm new to swift, coming from Objective-c, and I'm having trouble using the wrapper/unwrapper. I have the following in my...

Falling back maven dependency to more general classifier

maven dependency-management classification maven-dependency-plugin

Maven was designed mainly to support Java. I would like however, to store in maven repository some platform-dependent artifacts.