How can I center an element in wpf canvas using attached properties. Please help.
+2
A:
Something like this.
double left = (Canvas.ActualWidth - element.ActualWidth) / 2;
Canvas.SetLeft(element, left);
double top = (Canvas.ActualHeight - element.ActualHeight) / 2;
Canvas.SetTop(element, top);
mdm20
2010-02-05 17:24:56
can this be written inside a class which inherits a canvas class as an attached property.
Soham Dasgupta
2010-02-05 17:36:49
+2
A:
The only way I know to do this is to figure out the size of the canvas, and then set the properties based off that. This can be done using an event handler for SizeChanged on the canvas:
parentCanvas.SizeChanged += new SizeChangedEventHandler(parentCanvas_SizeChanged);
void parentCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
parentCanvas.SetLeft(uiElement, (parentCanvas.ActualWidth - uiElement.ActualWidth) / 2);
parentCanvas.SetTop(uiElement, (parentCanvas.ActualHeight - uiElement.ActualHeight) / 2);
}
Robin
2010-02-05 17:30:47
It should, yes. It will fire whenever the ActualWidth/ActualHeight properties of the canvas are changed. (i.e. during layout updating)
Robin
2010-02-05 18:27:27