尝试更新 ViewModel 中的 Ui 属性时 DispatcherQueue null

Tin*_*ren 1 c# data-binding desktop xaml winui-3

在桌面应用程序的 WinUI 3 中,我有一个要更新的属性,该属性通过x:Bind.

我想像Dispatcher在 WPF 中那样使用 UI 线程并避免在更新 prop 时出现线程错误:

System.Runtime.InteropServices.COMException: 'The application called an interface that was marshalled for a different thread. (0x8001010E (RPC_E_WRONG_THREAD))'

当我尝试时,我只是不确定如何在 WinUI 3 中执行此操作

DispatcherQueue.GetForCurrentThread().TryEnqueue(() =>
{
    AeParty.OnSyncHub = false; // Prop bound in ui using x:Bind
});
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

在此输入图像描述

DispatcherQueue.GetForCurrentThread()一片空白

我也尝试过:

this.DispatcherQueue.TryEnqueue(() =>
{
    AeParty.OnSyncHub = false;
});
Run Code Online (Sandbox Code Playgroud)

但它不会编译:

在此输入图像描述

然后我发现了这个GitHub 问题,所以我尝试了:

SynchronizationContext.Current.Post((o) =>
{
    AeParty.OnSyncHub = false;

}, null);
Run Code Online (Sandbox Code Playgroud)

这可行,但为什么我无法使用虚拟机中的调度程序进入 UI 线程?

mm8*_*mm8 6

DispatcherQueue.GetForCurrentThread()DispatcherQueue仅当在实际具有 的线程上调用时才返回 a DispatcherQueue。如果您在后台线程上调用它,则确实不会DispatcherQueue返回任何内容。

因此,技巧是在 UI 线程上调用该方法并将返回值存储在一个变量中,然后从后台线程使用该变量,例如:

public sealed partial class MainWindow : YourBaseClass
{
    public MainWindow()
    {
        this.InitializeComponent();
    }

    public ViewModel ViewModel { get; } = new ViewModel();
}

public class ViewModel : INotifyPropertyChanged
{
    private readonly DispatcherQueue _dispatcherQueue = DispatcherQueue.GetForCurrentThread();

    public ViewModel()
    {
        Task.Run(() => 
        {
            for (int i = 0; i < 10; i++)
            {
                string val = i.ToString();
                _dispatcherQueue.TryEnqueue(() =>
                {
                    Text = val;
                });
                Thread.Sleep(2000);
            }
        });

    }
    private string _text;
    public string Text
    {
        get { return _text; }
        set { _text = value; NotifyPropertyChanged(nameof(Text)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)