0

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?

Corbie
  • 819
  • 9
  • 31
  • 1
    Click event will not be removed, but being queued and being executed after ListBox update. And if you do things right, there is no block of button event, which perhap there are something wrong with your thread code (being synchronized with UI thread). – NoName Feb 29 '16 at 09:05
  • Unfortunately the handler is either called immediately (seems to work only between the `ListBox` updates) or it's never called. The BackGroundWorker is just writing to the `public ObservableCollection`. – Corbie Feb 29 '16 at 09:23
  • 3
    The problem is laid at your C# code behind, not the XAML. If you interested in fix it, post your C# code as detail as posiible. – NoName Feb 29 '16 at 09:30

2 Answers2

1

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.

Community
  • 1
  • 1
Watsontap
  • 152
  • 8
0

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 ;-)

Corbie
  • 819
  • 9
  • 31