简体   繁体   中英

wpf c# load user control in a separate thread

when user clicks on one of the available items (modules) available in his list I will use following code to create a new instance of selected item (user control) and then add it to my tabGroupArea .

object uc = Activator.CreateInstance(Type.GetType("myNamespace." + selectedItem.Parameter1Value), selectedItem);
Infragistics.Windows.DockManager.ContentPane contentPane = new Infragistics.Windows.DockManager.ContentPane();
contentPane.Content = uc;
tabGroupArea.Items.Add(contentPane);

the problem that I have is when the selectedItem has usercontrols inside it initializeComponent() will take a while to complete meanwhile the application will freeze and user can't do any thing ,I tried different ways to put

object uc = Activator.CreateInstance(Type.GetType("myNamespace." + selectedItem.Parameter1Value), selectedItem);

in a separate thread (Backgroundworker,thread and delegate) so I would be able to show user a loadin page .but I couldn't find anyway to do that . any help would be appreciated . thanks.

See this blog post .

Catel uses this approach for the PleaseWaitWindow .

the code below does it:

public partial class Window1 : Window
    {
        public delegate void CreateCanvasHandler(Grid parent, int index);

        public Window1()
        {
            InitializeComponent();

            int count = 10000;

            this.TestCreateAsync(count);
        }

        private void TestCreateAsync(int count)
        {
            for (int i = 0; i < count; i++)
            {
                //check the DispatecherOperation status
                this.LayoutRoot.Dispatcher.BeginInvoke(new CreateCanvasHandler(this.CreateCanvas),
                    DispatcherPriority.Background,
                    new object[2] 
                    { 
                        this.LayoutRoot,
                        i
                    });   
            }
        }

        private void CreateCanvas(Grid parent,
            int index)
        {
            Canvas canvas = new Canvas()
            {
                Width = 200,
                Height = 100
            };

            canvas.Children.Add(new TextBlock()
            {
                Text = index.ToString(),
                FontSize = 14,
                Foreground = Brushes.Black
            });

            Thread.Sleep(100);

            parent.Children.Add(canvas);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM