WPF C# - Editing a listbox from another thread

后端 未结 3 994
萌比男神i
萌比男神i 2020-12-29 13:32

I realize what I\'m doing is probably pretty silly, but I\'m in the middle of learning WPF and would like to know how to do this.

I have a window with a listbox on i

3条回答
  •  一个人的身影
    2020-12-29 14:11

    You can also use the Action delegate with anonymous methods to update the main thread from the worker thread. For more information on the Action class you could look here :

    http://msdn.microsoft.com/en-us/library/018hxwa8.aspx

    If you would like to update the listbox from multiple points I suggest explicitally setting the delegate, however if you just wish to update the thread at a single point in a method with a single call it could be done as follows :

            listbox.Dispatcher.BeginInvoke(new Action(delegate()
            {
                listbox.Items.Add(item); //where item is the item to be added and listbox is the control being updated.
            }));
    

    Note that I use the Action class as it takes encapsulates a method that has a single parameter (in this case a listItem).

提交回复
热议问题