【问题标题】:Dispatcher' does not contain a definition for 'InvokeAsync' and no extension method 'InvokeAsync'Dispatcher 不包含“InvokeAsync”的定义,也没有扩展方法“InvokeAsync”
【发布时间】:2018-02-11 15:16:30
【问题描述】:

我有错误,这是我的代码。

private void ComboBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _comboBox.Dispatcher.InvokeAsync(() => ContentChanged?.Invoke(sender, EventArgs.Empty));
        }

它说Dispatcher' does not contain a definition for 'InvokeAsync' and no extension method 'InvokeAsync' accepting a first argument of type 'Dispatcher' could be found (are you missing a using directive or an assembly reference? wpf 我迷路了,我需要这些帮助。谢谢。

【问题讨论】:

  • 写成_comboBox.Dispatcher.InvokeAsync((Action)(() => ContentChanged?.Invoke(sender, EventArgs.Empty)));
  • @RandRandom 同样问题先生...

标签: c# .net wpf mvvm dispatcher


【解决方案1】:

Dispatcher.InvokeAsync 绝对是.NET 4.5 的现有方法。如果您尝试为 .NET 4.0 或更早版本进行编译,则会看到该错误。

它的效果与您调用Dispatcher.BeginInvoke 的效果相同。区别在于BeginInvoke 接受委托(需要从 lambda 进行强制转换),而 InvokeAsync 不接受,因为它接受 Action。这样做是为了重构 API,但不会破坏仍然使用 BeginInvoke 的代码。详情请见this thread

.NET 4.5 之前

_comboBox.Dispatcher.BeginInvoke((Action)(() => {
    ContentChanged?.Invoke(sender, EventArgs.Empty);
}));

从 .NET 4.5 开始

_comboBox.Dispatcher.InvokeAsync(() => {
    ContentChanged?.Invoke(sender, EventArgs.Empty);
});

【讨论】:

    猜你喜欢
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    相关资源
    最近更新 更多