如果我在后面的代码中使用绑定,单击更改 IsBusy 后会出现错误
"The calling thread cannot access this object because a different thread owns it"
xml:
<Button x:Name="AsyncCommand"
Height="20"
Content="PushAsync"/>
<ProgressBar x:Name="IsBusy"
Height="20"/>
CS:
this.Bind(ViewModel, x => x.IsBusy, x => x.IsBusy.IsIndeterminate);
this.BindCommand(ViewModel, x => x.AsyncCommand, x => x.AsyncCommand);
视图模型:
public class TestViewModel : ReactiveObject
{
public TestViewModel()
{
AsyncCommand = new ReactiveAsyncCommand();
AsyncCommand
.RegisterAsyncFunction(x =>
{ IsBusy = true; Thread.Sleep(3000); return "Ok"; })
.Subscribe(x => { IsBusy = false; });
}
private bool isBusy;
public bool IsBusy
{
get { return isBusy; }
set { this.RaiseAndSetIfChanged(x => x.IsBusy, ref isBusy, value); }
}
public ReactiveAsyncCommand AsyncCommand { get; protected set; }
}
但是,如果我在 xaml 中进行绑定,则一切正常,如下所示:
CS:
DataContext = new TestViewModel();
xml:
<Button x:Name="AsyncCommand"
Height="20"
Content="PushAsync"
Command="{Binding AsyncCommand}"/>
<ProgressBar x:Name="IsBusy"
Height="20"
IsIndeterminate="{Binding IsBusy}"/>
为什么会这样?