在我的应用程序中,我有一个命令,我只希望用户能够在尚未运行时进行触发。有问题的命令绑定到WPF按钮,这意味着如果CanExecute为false,它将自动禁用该按钮。到目前为止,一切都很好。
不幸的是,该命令执行的操作是长期运行的操作,因此它需要在其他线程上进行。我不认为这会是一个问题...但是似乎是。
我提取了一个最小的样本来显示问题。如果绑定到按钮(通过LocalCommands.Problem静态引用),则将根据需要禁用该按钮。当辅助线程尝试更新CanExecute时,将从System.Windows.Controls.Primitives.ButtonBase内部引发InvalidOperationException。
解决此问题的最合适方法是什么?
下面的示例命令代码:
using System;
using System.Threading;
using System.Windows.Input;
namespace InvalidOperationDemo
{
static class LocalCommands
{
public static ProblemCommand Problem = new ProblemCommand();
}
class ProblemCommand : ICommand
{
private bool currentlyRunning = false;
private AutoResetEvent synchronize = new AutoResetEvent(false);
public bool CanExecute(object parameter)
{
return !CurrentlyRunning;
}
public void Execute(object parameter)
{
CurrentlyRunning = true;
ThreadPool.QueueUserWorkItem(ShowProblem);
}
private void ShowProblem(object state)
{
// Do some work here. When we're done, set CurrentlyRunning back to false.
// To simulate the problem, wait on the never-set synchronization object.
synchronize.WaitOne(500);
CurrentlyRunning = false;
}
public bool CurrentlyRunning
{
get { return currentlyRunning; }
private set
{
if (currentlyRunning == value) return;
currentlyRunning = value;
var onCanExecuteChanged = CanExecuteChanged;
if (onCanExecuteChanged != null)
{
try
{
onCanExecuteChanged(this, EventArgs.Empty);
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.Message, "Exception in event handling.");
}
}
}
}
public event EventHandler CanExecuteChanged;
}
}
Run Code Online (Sandbox Code Playgroud)
更改:
onCanExecuteChanged(this, EventArgs.Empty);
至:
Application.Current.Dispatcher.BeginInvoke((Action)(onCanExecuteChanged(this, EventArgs.Empty)));
Run Code Online (Sandbox Code Playgroud)
编辑:
这样做的原因是WPF正在侦听这些事件并试图在UI元素中执行操作(IE IsEnabled在切换Button),因此必须在UI线程中引发这些事件。
| 归档时间: |
|
| 查看次数: |
2212 次 |
| 最近记录: |