我想关闭我的视图模型中的 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(); });
同样的情况也会发生。 我想知道是否有解决方案或更好的方法可以从其他地方关闭弹出窗口而不转移弹出窗口的句柄。
我在代码中做到了这一点
PopupPage p = new PopupPage();
Application.Current.MainPage.ShowPopup(p);
await new TaskFactory().StartNew(() => { Thread.Sleep(5000); });
p.Close();
试试这个
<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();
}
}