Search code examples
c#wpfmultithreadingdata-bindingblockingcollection

How to bind a BlockingCollection to a WPF Listivew


I am having a BlockingCollection defined in my ViewModel which gets updated on by different threads. I am using this BlockingCollection to populate the ListView. But the newly added item in this collection is not getting reflected on the UI. I need a BlockingCollection because I am having a Multi threaded operation going on where this Collection may be updated by different threads, I want to ensure thread safety as such decided to use BlockingCollection

My ViewModel is :

public BlockingCollection<WorklistItem> ListSource { get; set; }

In the xaml I am setting this BlockingCollection to populate the List view as

 <ListView x:Name="MyList" HorizontalAlignment="Left" Height="263" Margin="5,200,0,0" VerticalAlignment="Top" Width="515" Grid.Column="0" AutomationProperties.IsColumnHeader="True" 
                              SelectedItem="{Binding SelectedItem}"
                              ItemsSource ="{Binding ListSource}" >

Solution

  • Your simplest approach would be to start with an observablecollection and add locking and synchronisation. Using BindingOperations.EnableCollectionSynchronization

    If you instead specifically need functionality in a blocking collection then you could inherit observablecollection, implement iproducerconsumercollection https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.iproducerconsumercollection-1?view=netframework-4.8 then use your new collection as the base type of your blockingcollection. When you new up a blockingcollection you can give it an underlying collection type other than the default. If you're not aware you can do that follow this link and scroll down https://learn.microsoft.com/en-us/dotnet/standard/collections/thread-safe/blockingcollection-overview