I'm adding controls programmatically to a canvas which is all just wonderful...
var newControlPoint = new ControlPoint() { Width = 10, Height = 10 };
newControlPoint.SetResourceReference(Control.TemplateProperty, "ControlPoint");
SetCanvasPosition(newControlPoint, position.X - (newControlPoint.Width / 2), position.Y - (newControlPoint.Height / 2));
canvas.Children.Add(newControlPoint);
newControlPoint.UpdateLayout();
... but I'm coming unstuck when I attempt to remove the hardwired Width and Height settings from the first line...
var newControlPoint = new C开发者_JS百科ontrolPoint();
...the canvas positioning doesn't seem to take effect and the newly created control winds up at {0,0}.
Any ideas?
Two problems:
- The Width and Height properties won't be set because you haven't explicitly set them. It's ActualWidth and ActualHeight you want, which are set by WPF.
- The controls haven't been laid out yet, so ActualWidth and ActualHeight will be zero.
To work around the problem you could:
- Use databinding instead of doing a one-off calculation.
- Attach the positioning logic to the control's Loaded event so it has been positioned.
- Use Dispatcher.BeginInvoke to run the layout logic in a separate message that runs at a lower priority to layout, thus ensuring the ActualWidth and ActualHeight have been calculated and assigned.
精彩评论