I have a Controls.Canvas with several shapes on it and would like to add textual labels that are centered on given points (I’m drawing a tree with labelled vertices). What is the simplest way to do this programmatically in WPF?
I have tried setting RenderTransform and calling Controls.Canvas.SetLeft etc. but neither position the label where I want it. WPF seems to support positioning only at given left, right, top and bottom coordinates and not centered on a given coordinate and the Width property is NaN and the ActualWidth property is 0.0 when I construct the Canvas.
You could achieve this by binding the margin of the label to the
ActualWidthandActualHeightof the label, and multiplying these values with -0.5. This moves the label left by half its width; and it moves the label upwards by half its height.Here is an example:
XAML:
The red rectangle highlights the coordinate (40, 40) on which the label “MMMMMM” is centered.
Converter:
The result looks like this:
In order to do that programmatically, define an attached property
Mover.MoveToMiddle, like this:Setting
Mover.MoveToMiddletotruemeans that the margin of that framework element is automatically bound to its actual width and height such that the framework element is moved to its center point.You would use it in your XAML code like this:
An alternative would be to bind to
RenderTransforminstead ofMargin. In this case, the converter would returnand the attached property’s callback method would contain these lines:
This alternative has the advantage that the effect of the attached property is visible in the Visual Studio designer (which is not the case when setting the Margin property).