Reputation: 1066
I have a WPF window with a ListBox
, that is bound to a public ObservableCollection<String>
, that is being updated by another thread (BackGroudWorker
).
<ListBox Name="ListBox"
ItemsSource="{Binding MyCollection}"
... />
In the same window I have a Button
with click handler:
<Button Content="Close"
Click="Button_LogWindow_closeButton_Click"
... />
This handler usually not called when I click the button while the ListBox is being updated. Although it works perfectly when the background thread has finished and the ListBox
is not being updated any more.
This looks to me like the button click event is being removed from the queue before it's handler can be called. Am I right?
Do you know how to fix this?
Upvotes: 0
Views: 133
Reputation: 1066
I have found the mistake. Every time the window was updated the function ListBox.Focus()
was called. That seems to have been done for keeping the window at topmost position. I have changed the XAML file to this:
<Window ...
Topmost="True"
... />
This should be the way it's meant to be ;-)
Upvotes: 0
Reputation: 162
It's hard to say without seeing your code, but your GUI thread is probably so busy updating the ListBox on every call to the ObservableCollection's Add method that the mouse click event is not handled.
If your background thread is using Dispatcher.Invoke or Dispatcher.BeginInvoke to add items to the ObservableCollection, you can lower the priority (to Dispatcher.Background, for example) in order to give click events a chance to be handled.
You could also use an ObservableCollection with an add range method that only raises the INotifyCollectionChanged.CollectionChanged event once for a collection of items instead of for each item. See this answer or Microsoft's own BulkObservableCollection as examples.
Upvotes: 1