Dynamically adding objects

Oct 20, 2008 at 5:45 PM
You mentioned that the UIElements needed to be drawn first to determine their boundries. I know in WPF I have used Measure() and Arrange() on elements that I just created to get their size before displaying them visually. These are FrameworkElement methods, but all UIElements are Framework elements so this may help out. An example would be to cast the UIElement as a FrameworkElement, call measure and arrange on that guy to allow that guy to be as large as he wants to:

FrameworkElement element = passedInAsUIElement as FrameworkElement;
element.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
element.Arrange(new Rect(new Point(0, 0), element.DesiredSize));

Hopefully this helps!
Oct 20, 2008 at 6:05 PM
Thanks Aquaseal!

Yeah, the problem I have is that the VisualTreeHelper.FindElementsInHostCoordinates method cannot do a HitTest on a UIElement until it is drawn to the screen.

I'll try and see if Measure and Arrange are a solution to the problem.

Oct 20, 2008 at 6:16 PM
Could you also set the Visibility to Collapsed on the UIElement, add it to the screen and then once the HitTest is complete set the Visibility to Visible? Maybe not the best way to achieve this, but something a little more secure than a timer ... I think.
Oct 20, 2008 at 6:21 PM
Yeah, you could even set the Opacity to zero - but I don't think either of those helps with the fact that FindElementsInHostCoordinates needs the element on the screen in order to do the HitTest?

So, in short, the issue is that a XAML element added through code cannot use FindElementsInHostCoordinates until after it is drawn to the screen. I tried plugging into different events, but so far the "delayed timer" approach is all I have working.

Thanks for the ideas, keep them coming, and I'll try the Measure/Arrange approach too...
Oct 3, 2009 at 12:05 AM

This is also an issue if you add a Path element via the designer and set its visibility to Collapsed.  Something I just encountered myself, and not an unlikely scenario if you have elements that you want to reveal during gameplay (like if they're behind a hidden portal).  So far the only solution I see is using the opacity trick, or creating the element off screen then setting its visibility to collapsed before putting it in position (which I haven't actually tried in Silverlight, but is a common game programming trick).