views:

538

answers:

4

I am dynamically adding custom controls in Silverlight 2 but they are not visible. However, on examining the visual tree in Silverlight Spy I note that their visibility property is Visible and toggling it to Collapsed and back to Visible causes the controls to become visible.

What might I be doing wrong? Any ideas on what I should look for to resolve this?

+1  A: 

The first thing that comes to mind is what kind of container object are you using to create the dynamic controls, if any?

I could see how maybe adding controls without using a container might give you some issues. I can't say I've created many control objects dynamically, but I would think adding your items to a Stack Panel would be the easiest implementation.

A good test case might be to create a grid and assign grid locations for your controls as you create them.

Here's a link on how to do just this.

Overhed
If I'm not mistaken creating the objects and not adding them to a container would prevent them being in the visual tree at all.
Steve Crane
+1  A: 

Have you tried calling UpdateLayout() on the control you're adding them to?

mattmanser
+1  A: 

UpdateLayout() on the ParentControl shoudn't be necessary.

But don't forget my_parent_control.Add(UIElement mynewcontrol);

i.e. my_parent_control could be a stack panel.

Henrik P. Hessel
A: 

I've been able to solve the problem, which occurred when I was dynamically adding time periods to a timeline.

The controls I'm dynamically adding, to a canvas, have the following structure.

<Path x:Name="ribbonItem" Fill="Green">
  <Path.Data>
    <GeometryGroup>
      <RectangleGeometry x:Name="ribbonItemBackground" />
    </GeometryGroup>
  </Path.Data>
</Path>

The dimensions of the RectangleGeometry depend on three inputs, the date and time ranges of the timeline bar and timeline item (what I'm adding) and the dimensions of the bar (canvas).

The following method is called when any of the BarRange, ItemRange or BarSize properties of the object are set.

private void Resize()
{
if (_itemRange != null && _barRange != null && _barSize != Size.Empty)
  {
    ribbonItemBackground.Rect = ItemRectangle();
  }
}

This caused the drawing problem mentioned in my question and the solution was to add

ribbonItem.InvalidateMeasure();

immediately after setting ribbonItemBackground.Rect.

Steve Crane
Good for you! :) You should add information like that next time you ask a question.
Henrik P. Hessel