MVVM Light:RelayCommand:重用命令还是创建新实例?
在 ViewModel 中定义 RelayCommand 时,通常使用 once [延迟或在构造函数中] 完成(请参阅 此处 为例)。
但这安全吗? 如果来自同一实例的多个 RelayCommand 排队(多次单击 GUI 上的同一按钮),并且对于第一个命令,“CanExecute”更改为 false,其他排队的命令是否也会被取消? ? 我可以想象这不是正确的行为?
When defining a RelayCommand in the ViewModel, this is normally done using once [lazy or in constructor] (see here for examples).
But is this safe ?
What if multiple RelayCommands from the same instance are queued (multiple clicks from same button on the GUI), and for the first command the 'CanExecute' is changed to false, will the other queued commands also be cancelled ?
I can imagine that this not the correct behavior ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的执行操作应该仔细检查命令是否可以执行。 CanExecute 是对与命令绑定的任何内容的提示,但您的 ViewModel 不应该对如何调用执行操作做出任何假设。
Your execute action should double check whether the command can execute or not. CanExecute is a hint for anything binding to the command, but your ViewModel shouldn't make any assumptions about how the execute action is being called.
多个命令不会排队。 RelayCommand 是数据绑定的,因此它将在 UI 线程上执行。只有一个 UI 线程,因此 RelayCommand 的一个实例必须在输入下一次单击之前完成执行。如果您有长时间运行的操作,通常会禁用命令并启动异步操作或生成后台作业,然后当 UI 发布时,在处理下一次单击之前该命令将已被禁用。
Multiple commands won't be queued. The RelayCommand is data-bound so it will be executed on the UI thread. There is only one UI thread, so one instance of the RelayCommand would have to finish execution before the next click entered. If you have long-running operations, you'll typically disable the command and kick of an asynchronous operation or spawn a background job, and then when the UI is released, the command will already be disabled before the next click is processed.