Reputation: 339
Excerpt of code from my Model view.
private ObservableCollection<MessageAbstract> _messages;
/// <summary>
/// Gets the Messages property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public ObservableCollection<MessageAbstract> Messages
{
get
{
return _messages;
}
set
{
if (_messages == value)
{
return;
}
_messages = value;
RaisePropertyChanged(() => Messages);
}
}
private CollectionViewSource _messageView;
public CollectionViewSource MessageView
{
get { return _messageView; }
set
{
if (_messageView == value) return;
_messageView = value;
RaisePropertyChanged(() => MessageView);
}
}
private void MessageArrived(Message message){
Application.Current.Dispatcher.Invoke(DispatcherPriority.Send,
new Action(() =>Messages.Add(message));
}
public ModelView(){
MessageView = new CollectionViewSource{Source = Messages};
}
When my call back from another service is called I'm still getting an this exception on the Messages.Add(message) The exception message is as follows. "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread."
Excerpt of code from my view.
<ListBox x:Name="MessageList" ItemsSource="{Binding MessagesView}">
I've checked that the Application.Current.Dispatcher is the same as the MessageList.Dispatcher so now I'm lost about why I cannot add to my view. My main goal is I have a search box that uses the collection view source filter to filter the message list.
Got the answer
I found my answer the mistake was the same as the #2 point in the answer below. I just encapsulated all the creation of my collections in the App dispatcher.
Application.Current.Dispatcher.Invoke(DispatcherPriority.Send,new Action(
() => { Messages = new ObservableCollection<MessageAbstract>();
MessageView = new CollectionViewSource { Source = Messages };
));
WPF: Accessing bound ObservableCollection fails althouth Dispatcher.BeginInvoke is used
We've run into this problem before ourselves. The issue is twofold:
1- Make sure that any changes to the SourceCollection are on the main thread (you've done >that).
2- Make sure that the creation of the CollectionView was also on the main thread (if it were >created on a different thread, say in response to an event handler, this will not usually be >the case). The CollectionView expects modifications to be on "its" thread, AND that "its" >thread is the "UI" thread.
Upvotes: 2
Views: 2593
Reputation: 1432
I had the same thread issues while binding directly to a CollectionViewSource
. I fixed the problem by binding my listbox to a CollectionView
object instead.
In your case, you would simply need to change your listbox declaration to:
<ListBox x:Name="MessageList" ItemsSource="{Binding MessagesView.View}">
Hope this helps you.
Upvotes: 1