ReactiveCommand:CanExecute 不更新
ReactiveCommand: CanExecute not updating
我正在尝试在 ViewModel 的构造函数中创建一个 ReactiveCommand:
IObservable<bool> canExecute = this
.WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
(insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0);
canExecute.Subscribe(x => this.Logger.LogInformation("Can execute changed: {0}", x));
this.ConvertCmd = ReactiveCommand.CreateAsyncTask(canExecute, ConvertCmdExecute);
ConvertCmd 然后绑定到我的 GUI 中按钮的命令 属性,
<Button Content="Convert" Command="{Binding ConvertCmd, Mode=OneWay}" />
但是,GUI 按钮保持灰色并且永远不会启用
注意几点:
- 在我的记录器中,我看到了几个更新 "Can execute changed: ...",最新/最后一个值为 True(正如预期的那样)。所以看起来我的 IObservable canExecute 确实创建了正确的、预期的值序列;最终以 true 结尾的序列。
- 当我使用 ReactiveCommand.CreateAsyncTask(ConvertCmdExecute) 创建命令时 - 即省略 canExecute 参数 - 按钮被启用并在单击时执行 ConvertCmdExecute,也正如预期的那样。所以看起来数据绑定本身等工作。
我在这里不知所措。有谁知道为什么在我原来的场景中按钮永远不会启用?
像往常一样,在这个问题上花了几个小时后,我在发布这个问题后不久就找到了自己的答案...
这似乎是一个线程问题。
订阅在未知的、可能不同的线程上执行。下面修复了代码——老实说,我不完全确定为什么有必要在 Dispatcher 上使用这个 运行。
IObservable<bool> canExecute = this
.WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
(insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0)
.ObserveOnDispatcher(); // this fixes the issue
我正在尝试在 ViewModel 的构造函数中创建一个 ReactiveCommand:
IObservable<bool> canExecute = this
.WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
(insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0);
canExecute.Subscribe(x => this.Logger.LogInformation("Can execute changed: {0}", x));
this.ConvertCmd = ReactiveCommand.CreateAsyncTask(canExecute, ConvertCmdExecute);
ConvertCmd 然后绑定到我的 GUI 中按钮的命令 属性,
<Button Content="Convert" Command="{Binding ConvertCmd, Mode=OneWay}" />
但是,GUI 按钮保持灰色并且永远不会启用
注意几点:
- 在我的记录器中,我看到了几个更新 "Can execute changed: ...",最新/最后一个值为 True(正如预期的那样)。所以看起来我的 IObservable canExecute 确实创建了正确的、预期的值序列;最终以 true 结尾的序列。
- 当我使用 ReactiveCommand.CreateAsyncTask(ConvertCmdExecute) 创建命令时 - 即省略 canExecute 参数 - 按钮被启用并在单击时执行 ConvertCmdExecute,也正如预期的那样。所以看起来数据绑定本身等工作。
我在这里不知所措。有谁知道为什么在我原来的场景中按钮永远不会启用?
像往常一样,在这个问题上花了几个小时后,我在发布这个问题后不久就找到了自己的答案...
这似乎是一个线程问题。 订阅在未知的、可能不同的线程上执行。下面修复了代码——老实说,我不完全确定为什么有必要在 Dispatcher 上使用这个 运行。
IObservable<bool> canExecute = this
.WhenAnyValue(x => x.InsertableItems, x => x.IsRefreshing,
(insertableItems, isRefreshing) => !isRefreshing && insertableItems > 0)
.ObserveOnDispatcher(); // this fixes the issue