Geeks With Blogs
shmoolca wpf programming

Most articles and tutorials that I have seen about BackgroundWorker describing method to update GUI especially ProgressBar or downloading data in background. Today I start to wonder what if I would like to create real huge GUI in background, for example adding 10000 buttons to StackPanel. The solution is really simple. Basically I cannot create new Visual object in BackgroundWorker directly. I have to create an object in Dispather. Invoke thread. The code looks as following.

Procedural code:

    public partial class Window1 : System.Windows.Window

    {

 

        public Window1()

        {

            InitializeComponent();

            for (int i = 1; i < 10000; i++)

            {

                BackgroundWorker bw = new BackgroundWorker();

                bw.DoWork += new DoWorkEventHandler(Dowork);

                bw.RunWorkerAsync(i.ToString());

            }

        }

        Button tempButton = new Button();

        void Dowork(object sender, DoWorkEventArgs e)

        {

                Button b;

                m_Grid.Dispatcher.Invoke((ButtonInvoke)delegate()

                {

                    b = new Button();

                    b.Content = e.Argument;

                    m_Grid.Children.Add(b);

                });

        }

        delegate void ButtonInvoke();

    }

XAML code:

<Window x:Class="threads.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="threads" Height="300" Width="300"

    >

  <ScrollViewer VerticalScrollBarVisibility="Auto">

  <StackPanel x:Name="m_Grid">

  </StackPanel>

  </ScrollViewer>

</Window>

Posted on Friday, October 9, 2009 10:57 AM Memorandum | Back to top


Comments on this post: Creating GUI using BackgroundWorker

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Anna Bauza | Powered by: GeeksWithBlogs.net