3

I try to bind simple synchronous command with ReactiveUI.

public ICommand ClickCommand { get; set; }

public bool IsClicked;

public MainViewModel()
{
    ClickCommand = ReactiveCommand.Create(OnClick);
}

private void OnClick()
{
    //just example of fast action   
    IsClicked = true;
}

But when I invoke it I get an error:

System.InvalidOperationException: The calling thread can not access this object, since the owner of this object is another thread

In the invocation stack i can see it is about System.Windows.Controls.Primitives.ButtonBase.UpdateCanExecute(). How can i avoid changes of ReactiveCommand.CanExecute or force it to invoke in the UI thread?

Gotcha
  • 45
  • 1
  • 4
  • Does it work if you define the property like this? `public ReactiveCommand ClickCommand { get; }` – mm8 Sep 07 '18 at 11:54
  • 1
    I've seen this too many times. Definitely belongs in a FAQ section somewhere. Try adding the ReactveUI.WPF package to your project. It contains a number of WPF-related threading packages registered with ReactiveUI's dependency inversion system. If this solves your issue, I'll add it as an official answer. – Colt Bauman Sep 07 '18 at 12:40
  • @mm8 Doesn't change anything – Gotcha Sep 10 '18 at 07:49
  • @ColtBauman it helps! Thank you so much! – Gotcha Sep 10 '18 at 07:52

2 Answers2

4

I wish there were a better error message. Try adding the ReactiveUI.WPF package to your project. It contains a number of WPF-related threading packages registered with ReactiveUI's dependency inversion system. You'll also find this information in step 2 of the getting started documentation. Happy coding!

thumbmunkeys
  • 20,606
  • 8
  • 62
  • 110
Colt Bauman
  • 564
  • 3
  • 9
1

I was having the same issue for weeks. My exception was throw when a menu item was trying to update its state (the ReactiveCommand is bound to a menu item).

Adding ReactiveUI.WPF to the project solved the issue.

Felix
  • 2,673
  • 3
  • 30
  • 38