我想测试一些东西,所以我构建了一个小视图&带有一个按钮和一个ListBox的视图模型。当我单击该按钮时,我运行RunCommand,如下面的代码所示。我不明白为什么调度程序不触发我想让它运行的操作。
以下是视图模型代码:
public class ViewModel
{
private ObservableCollection<string> _items = new ObservableCollection<string>();
private ICommand _runCommand;
public ICommand RunCommand { get { return _runCommand ?? (_runCommand = new ActionCommand(RunCommandAction)); } }
private void RunCommandAction()
{
Task.Factory.StartNew(() =>
{
if (Thread.CurrentThread == EnvironmentData.UIThread)
_items.Add("Eldad");
else
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => _items.Add("Eldad")));
});
}
public IEnumerable<string> Items
{
get { return _items; }
}
public ViewModel()
{
_items.Add("Shahar");
}
}任何想法都会很棒
谢谢
发布于 2013-06-11 18:22:36
Dispatcher.CurrentDispatcher -获取当前正在执行的线程的调度程序,如果还没有与线程关联的调度程序,则创建一个新的调度程序。
因为您使用的是Task.Factory.StartNew,所以执行此操作的线程不是主线程。如果要对UI线程使用调度程序,则必须使用App.Current.Dispatcher
https://stackoverflow.com/questions/17041498
复制相似问题