Gotcha
Gotcha

Reputation: 45

ReactiveUI sync ReactiveCommand invocation cause System.InvalidOperationException

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?

Upvotes: 3

Views: 746

Answers (2)

Colt Bauman
Colt Bauman

Reputation: 672

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!

Upvotes: 5

Felix
Felix

Reputation: 2851

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.

Upvotes: 1

Related Questions