Question

I'm having a Class Item : UserControl , I need to add these items in a Panel (like in Grid) multipletimes.

Note : I will clear and add those items very often.

On the performance and memory consumption basic, which method can i go for?

either, (i).just add those items (UserControl) like the below

 for (int i = 0; i < myCollection.Count; i++)
  {
    Item _item = new Item();
    _item.Name = "Item - "+i.ToString();
    panel1.Children.Add(_item);      
  }

or

can i go with

 <Grid ItemSource="myCollection" >
     <ItemsControl >
           <ItemsControl.ItemTemplate>
                 <DataTemplate>
                      //User control's template
                 </DataTemplate>
            </ItemsControl.ItemTemplate>
      </ItemsControl>
  </Grid>

Thanks in advance. Joy Oyiess Rex K

Was it helpful?

Solution

Regarding performance the worst thing you can do is create new instances of a UserControl over and over again. So basically what your solution (i) is suggesting.

Why? Because the xaml of a UserControl is always parsed for every instance you are creating.

So what can be done? You could design your control as a templated control. This way the template xaml is only parsed once, and reused whenever you instantiate an new instance.

But it would still be inadvisable to create new instances in your code. Silverlight has item controls that are able to handle large lists of entries and that can manage to only instantiate visual elements for entries that are actually visible.

So I strongly recommend using an ItemsControl with a virtualizing panel (only instantiating visual elements for visible entries).

<ItemsControl>
    <ItemsControl.ItemsPanelTemplate>
        <VirtualizingStackPanel/>
    </ItemsControl.ItemsPanelTemplate>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <MyItemControl/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Some code for MyItemControl:

public class MyItemControl : Control
{
    public MyItemControl(){DefaultStyleKey=typeof(MyItemControl);}
}

Some xaml for the control's default template:

<Style TargetType="MyItemControl">
    <Setter Property="Template" Value="{StaticResource MyItemControlDefaultTemplate}"/>
</Style>

<ControlTemplate x:Key="MyItemControlDefaultTemplate" TargetType="MyItemControl">
...
</ControlTemplate>

OTHER TIPS

I don't think there is a real difference. I don't know about performance (i reckon XAML does the same as you under water), but memory consumption would be the same, since the control is created / garbage collected in both cases.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top