如何从 Viewmodel 关闭 MauiCommunityToolkit 弹出窗口

问题描述 投票:0回答:2

我想关闭我的视图模型中的 CommunityToolkit 弹出窗口。 我尝试使用

WeakReferenceMessenger
来接收这样的消息:

        public mypopup()
    {
        InitializeComponent();
        WeakReferenceMessenger.Default.Register<string, string>(this, "popup", (r, d) =>
        {
            Debug.WriteLine(message: "received message");
            if (d == "close")
            {
                WeakReferenceMessenger.Default.Unregister<string>(this);
                MainThread.BeginInvokeOnMainThread(() => { this.Close(); });
            }
        });
    }

在其他地方我用它来发送消息

WeakReferenceMessenger.Default.Send<string, string>("close", "popup");

第一个电话有效。第二次它会在

MauiPopup.windows.cs
函数 System.NullReferenceException
 中引发 
void CleanUp() Target.ContextFlyout = null;

我也在消息接收中尝试过这样的操作:

MainThread.BeginInvokeOnMainThread(() => { this.Close(); });

同样的情况也会发生。 我想知道是否有解决方案或更好的方法可以从其他地方关闭弹出窗口而不转移弹出窗口的句柄。

popup maui windows-community-toolkit maui-community-toolkit
2个回答
3
投票

我在代码中做到了这一点

        PopupPage p = new PopupPage();
        Application.Current.MainPage.ShowPopup(p);
        await new TaskFactory().StartNew(() => { Thread.Sleep(5000); });
        p.Close();

0
投票

试试这个

<Button
     Command="{Binding CloseClickCommand}"
     CommandParameter="{Binding Source={RelativeSource Mode=FindAncestor, AncestorType={x:Type mct:Popup}}}"
     Text="Close" />

...

public async Task CloseClickCommand(object obj)
{
    if (obj is Popup popup) 
    {
       popup.Close();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.