0

I can't find the right NuGet packet to install the invoke method. I have a wpf GUI and I have a separate thread that needs to update items in a listBox. I need the "Invoke" method in order to change the items in the listBox.

    public void displayPlayers(string players)
    {
        //spliting all the names.
        string[] names = players.Split(", ".ToCharArray());

        //Displaying the names.
        foreach (string name in names)
            this.Invoke((MethodInvoker)(() => playersListBox.Items.Add(name)));
    }
  • 1
    The `.Invoke` method is part of Winforms. You don't need to install it. And why have you said a "wpf GUI"? – Enigmativity Jul 02 '19 at 10:06
  • It should be `playersListBox.Invoke(new Action(() => playersListBox.Items.Add(name)));` – Alessandro D'Andria Jul 02 '19 at 10:07
  • @Enigmativity, Because of my lack of knowledge in this field... I'm really new to c# and wpf so my terminology is lacking. – Anthon Naivelt Jul 02 '19 at 10:10
  • @AlessandroD'Andria, It still gives me an error: Error CS1061 'ListBox' does not contain a definition for 'Invoke' and no accessible extension method 'Invoke' accepting a first argument of type 'ListBox' could be found (are you missing a using directive or an assembly reference?) Trivia_client C:\Users\antho\OneDrive\Desktop\Projects\Trivia_client\Trivia_client\WaitingRoom.xaml.cs 75 Active – Anthon Naivelt Jul 02 '19 at 10:12
  • @AnthonNaivelt I thought it was Winforms because of `using System.Windows.Forms;` – Alessandro D'Andria Jul 02 '19 at 10:15
  • @AlessandroD'Andria oh, I see. No, I'm using wpf. I need a way to change the items displayed in the listBox. – Anthon Naivelt Jul 02 '19 at 10:17
  • @AnthonNaivelt take a look at [this question](https://stackoverflow.com/questions/1644079/change-wpf-controls-from-a-non-main-thread-using-dispatcher-invoke). – Alessandro D'Andria Jul 02 '19 at 10:25
  • @AnthonNaivelt - Can you please edit your question to remove references to Winforms and make it clear you mean WPF? – Enigmativity Jul 02 '19 at 10:39

2 Answers2

1

Use the Dispatcher.Invoke() method. It is accessible via Application class (see more) or on the control itself. For more info see: Dispatcher.Invoke

Andro
  • 2,232
  • 1
  • 27
  • 40
0

This works for me:

await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() =>
{
    playersListBox.Items.Add(name);
}));

Or without await:

System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.ContextIdle, new Action(() =>
{
    playersListBox.Items.Add(name);
})).Wait();
Nenad
  • 316
  • 2
  • 14