开发者

WP7 add batches of elements to my scene

I have a scene in my WP7 app that holds around ~250 checkboxes with custom templates.

The checkboxes are all prepared (datawise) on a开发者_C百科 background thread, and that all works fine.

But when I go to add them to the Canvas, even if I use the Dispatcher it seems to totally bog down the UI thread.

Is there a nice way to add them in batches so that they appear almost gradually onto the scene?

This is my current implementation

        foreach (var cbData in container.ParamCheckBoxesToCreate)
        {
            CheckBox cb = new CheckBox
                                                  {
                                                      Template = (ControlTemplate)Resources[cbData.CB_TemplateName],
                                                       //more creation stuff
                                                  };
            Canvas.SetLeft(cb, cbData.CB_Left);
            Canvas.SetTop(cb, cbData.CB_Top);
            Canvas.SetZIndex(cb, 30);
            Dispatcher.BeginInvoke(new Action(() => MyCanvas.Children.Add(cb)));
        }

But adding 250 of these still kills the UI thread.

How can I add, say 10 at a time until I am done?


I would:

  1. Use a grid not the canvas as the parent container
  2. Add a batch of checkboxes to a container (possibly a stackpanel)
  3. Add the container to the grid
  4. Animate the container in
  5. repeat from step 2 until done


If you drive adding this from a background thread, you can add a call to Thread.Sleep(1) on the background thread between calls to the Dispatcher in order to let the UI thread process your work item. Here is a simplified example, adding Rectangles on a Canvas:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Thread thread = new Thread(ThreadProc);
    thread.Start();
}

void ThreadProc()
{
    for (int i = 0; i < 2800; i++)
    {
        Dispatcher.BeginInvoke(() => 
        {
            int index = LayoutRoot.Children.Count;
            Rectangle rect = new Rectangle()
            {
                Width = 10d,
                Height = 10d,
                Fill = new SolidColorBrush(Colors.Red),
            };
            int row = index / 4;
            int col = 10*(index % 70);
            Canvas.SetTop(rect, col);
            Canvas.SetLeft(rect, row);
            LayoutRoot.Children.Add(rect);
        });
        Thread.Sleep(1);                
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜