locked
Marshalls thread error when update element in observablecollection wpf silverlight

    Question

  • Hey

    I am doing a WP8.1 project. I have listview which is binding to observablecollection. Binding just working fine.

    and then the event triggered code failed at OnPropertyChanged("ConnectionStatus").

    I know this caused by a threading problem that the when executing the event method and trying to update UI but I am not in a UI thread, then it fails. Do you know if there is a way to solve this?

    I have known I can use Dispacher to start a background task, But I dont think it is relevant to this, since in this case the event just trigger when the thing happen, it is not like executing background task.  

    private void Item_Clicked(sender, arg) { .... ConnectionStatusChanged += DeviceConnectionStatusChanged; .... } private void DeviceConnectionStatusChanged(sender, arg) { //update a bound element in XAML PropertyChanged } XAML <Textbox x:Name = status binding { ConnectionStatus }...../> ViewModel String ConnectionStatus { get { return _connectionStatus; } set { if(value != _connectionStatus) _connectionStatus = value; OnPropertyChange("ConnectionStatus"); }

    }


    Jiajun Qiu

    Wednesday, September 24, 2014 6:49 PM

Answers

  • You should queue the update on a dispatcher thread:

    await Dispatcher.RunAsync((unused)=>
    {
        // update connection status here.
    });

    When the connection changes, run the above.  It will dispatch the call to update the value, which then will work, as it's on the dispatcher thread.


    Darin R.

    Wednesday, September 24, 2014 9:23 PM