Sonic Soul
Sonic Soul

Reputation: 24939

wpf binding: The calling thread cannot access this object because a different thread owns it

I am getting this error after raising NotifyPropertyChange event from a view model property.

I added (as a test) an UI Dispatcher.Invoke call on the setter which seems to have fixed the problem temporarily.

   public FeedTrackingSummary SelectedFeedTracking {
        get { return _selectedFeedTracking; }
        set { 
            Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => {
                _selectedFeedTracking = value; Notify("SelectedFeedTracking");
            }));
        }
    }

SelectedFeedTracking below is set by choosing a dropdown value which is bound to this property:

<ComboBox... SelectedItem="{Binding SelectedFeedTracking}"  />

the error happens after selecting a drop-down value. There is no other code setting this property. I guess my viewmodel is used in a background thread at the time this happens?

UPDATE

i tried removing the call to INotifyPropertyChanged, and set a totally different property, and the error still persists. so i guess this has to do with the accessibility of the whole viewmodel ?

        set { 
            SelectedCalc = -1;
        }

Upvotes: 1

Views: 1105

Answers (1)

Fede
Fede

Reputation: 44048

Some MVVM Frameworks (such as Caliburn.Micro, for example) have a base NotifyPropertyChanged class which automatically marshals property change notifications (by raising the PropertyChanged event) to the so-called "UI Thread".

So, instead of having to Application.Current.Dispatcher.Invoke(...) on every property setter, put that code in your Notify() method. Thus making sure every time you notify property changes in the ViewModel you do so in the UI thread.

Upvotes: 4

Related Questions