tags:

views:

25

answers:

1

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 ControlPoint();

...the canvas positioning doesn't seem to take effect and the newly created control winds up at {0,0}.

Any ideas?

A: 

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.

HTH,
Kent

Kent Boogaart
As it so happens, I didn't actually want to set the width and height in code behind at all. It was my attempts remove such code that uncovered the issues for me.Once I removed the division of the hieght and width as well, everything started to work once more.Presumably there was some exception happening but Visual Studio was not giving the slightest indication that anything was wrong (right up to and including being able to step through and past the offending code).
lzcd
And as someone else dutify pointed out just now, all the strange behavour can be accounted for due to Height and Width being set to NaN. e.g. x + NaN / y = NaN.
lzcd