David
David

Reputation: 273

UWP - Refresh ListView from a running async method

I have written a method which sends an UDP broadcast und recieves the results in a loop which are instantly written in to a List<String>. Since I'm using ReceiveAsync() it is running asynchronous.

My question is: how can I refresh the ListView in my UI each time the loop adds a string to my list. So I want the results to be displayed instantly on the screen as they appear in the list.

Code

do
{
    UdpReceiveResult result = await sclient.ReceiveAsync();
    ipList.Add(result.RemoteEndPoint.Address.ToString());
    // after this step I want the ListView to get refreshed
} while (sclient.Available != 0);

XAML ListView Code

<ListView x:Name="lbIps" HorizontalAlignment="Left" Height="174"
Margin="450,151,0,0" VerticalAlignment="Top" Width="298" />

Code behind XAML

 public async void btnBroadcast_Click(object sender, RoutedEventArgs e)
 {
    await ND2.run();
    lbIps1.ItemsSource = ND2.ipList;
 }

Upvotes: 0

Views: 3094

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39092

First of all you should bing the data to the ListView using data binding:

<ListView x:Name="lbIps" ItemsSource="{x:Bind IpList}" ... />

Now you have to actually create such property in the code-behind:

ObservableCollection<string> IpList => ND2.ipList;

Finally, change the type of ipList to ObservableCollection<string>. You no longer have to set the ItemsSource manually inside the btnBroadcast_Click method as it is bound directly to the ND2.ipList. Also, thanks to the fact that it is a ObservableCollection<string> any new items added will automatically be reflected in the UI.

**Note: ** Make sure, you don't create a new instance of the ipList, because the ListView would stay bound to the original instance. I presume ipList is a field or a property:

public ObservableCollection<string> ipLIst {get;} = new ObservableCollection<string>();

Now the property is initialized at the beginning and will not change. You can use Clear() method to remove all elements in the collection if necessary instead of setting a new instance.

Upvotes: 3

Related Questions