How to return a value with Dispatcher.Invoke?

后端 未结 5 1981
执念已碎
执念已碎 2020-12-20 10:42

Anyone knows how to return a value from Dispatcher.Invoke in wpf? I want to return the selected index for a ComboBox.

Thanks!

5条回答
  •  感情败类
    2020-12-20 11:32

    int result = -1;
    
    // this is synchronous
    myCombo.Invoke(() => 
    {
      result = myCombo.SelectedIndex;
    });
    
    return result;
    

    This is, of course, kind of clunky. Better design would be to implement INotifyPropertyChanged in your VM, create a SelectedIndex property and bind the SelectedIndex property of your combo box to it. INPC binds are thread-insensitive (3.5 or 4.0+, I don't remember which), so you can read and update these properties from different threads in your VM without worry.

提交回复
热议问题