On a button click I creat开发者_Python百科e a Rectangle and rotate it by 45 degrees. Then I add it to the canvas. Now once the rectangle is created, I try to get its bounds but it returns null. Please let me know why? And how to rectify the following:
private void OnLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Rectangle rectangle = new Rectangle();
rectangle.Width = 100;
rectangle.Height = 200;
rectangle.RenderTransform = new RotateTransform( 45, rectangle.Width / 2, rectangle.Height / 2);
rectangle.Fill = Brushes.RoyalBlue;
Canvas.SetLeft(rectangle,100);
Canvas.SetTop(rectangle, 100);
myCanvas.Children.Add(rectangle);
//re has empty values
Rect re = GetBounds(rectangle, myCanvas);
}
public Rect GetBounds(FrameworkElement of, FrameworkElement from)
{
Rect bounds = of.TransformToVisual(from).TransformBounds(new Rect(of.RenderSize));
return bounds;
}
The problem is the Rectangle hasn't undergone a layout pass yet, so Rectangle.RenderSize
will still be empty. The layout pass will be performed when you return control back to WPF i.e. when you return from OnLeftButtonDown.
精彩评论