开发者

Ability to modify control dissapears when no properties are set

开发者 https://www.devze.com 2022-12-19 17:18 出处:网络
I\'m adding controls programmatically to a canvas which is all just wonderful... var newControlPoint = new ControlPoint() { Width = 10, Height = 10 };

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:

  1. 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.
  2. The controls haven't been laid out yet, so ActualWidth and ActualHeight will be zero.

To work around the problem you could:

  1. Use databinding instead of doing a one-off calculation.
  2. Attach the positioning logic to the control's Loaded event so it has been positioned.
  3. 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.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号