我开始使用。net MAUI。我刚开始开发就遇到了一个问题。我想显示一个弹出窗口,我正在使用社区工具包。
我所做的就是:
我创建了一个新的。net MAUI应用程序项目,安装了社区工具包NuGet包(当然还有启动类中的。usemauiccommunitytoolkit),并为弹出窗口添加了一个XAML文件:
<?xml version="1.0" encoding="utf-8" ?>
<toolkit:Popup xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class="TestApp.ProfilePopup">
<VerticalStackLayout>
<Label Text="This is a very important message!" />
</VerticalStackLayout>
</toolkit:Popup>
我没有这个popup的分部类
我刚刚修改了MainPage上的按钮来显示弹出窗口:
private void OnCounterClicked(object sender, EventArgs e)
{
var popup = new ProfilePopup();
this.ShowPopup(popup);
}
如果我运行这个应用程序并点击按钮来显示弹出窗口,我将得到错误信息:
CommunityToolkit.Maui.Core.Handlers.PopupHandler found for TestApp.ProfilePopup is incompatible
如果我在c#中创建弹出窗口,它可以工作:
private void OnCounterClicked(object sender, EventArgs e)
{
var popup = new Popup
{
Content = new VerticalStackLayout
{
Children =
{
new Label
{
Text = "This is a very important message!"
}
}
}
};
this.ShowPopup(popup);
}
知道我做错了什么吗?
谢谢!
马库斯
我重现了错误信息。
原因:"我没有这个弹出窗口的局部类">。
那不行。没有这个,就没有InitializeComponent
呼叫。结果不是一个有效的视图。
要解决这个问题,
首先确保您已经在MauiProgram.cs
中注册了工具包:
using CommunityToolkit.Maui;
...
builder.UseMauiApp<App>().UseMauiCommunityToolkit();
那么你必须有
文件ProfilePopup.xaml.cs
包含:
public partial class ProfilePopup : CommunityToolkit.Maui.Views.Popup
{
public ProfilePopup()
{
InitializeComponent();
}
}
我使用以下步骤生成自定义视图:
- Project/Add New Item/. net MAUI ContentView (XAML).
- 给出名称"myview"。这将添加两个文件到项目:
MyView.xaml
和MyView.xaml.cs
。 - 在
MyView.xaml
中,添加所需的xmlns并更改基类。
:
<ContentView xmlns=...
...
x:Class=...>
...
</ContentView>
更改为:
<toolkit:Popup xmlns=
...
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
x:Class=...>
...
</toolkit:Popup>
- 在
MyView.xaml.cs
中,更改基类。
:
public partial class ProfilePopup : ContentView
更改为:
public partial class ProfilePopup : CommunityToolkit.Maui.Views.Popup
Microsoft页面上的文档应该完成(我用作模板):
https://learn.microsoft.com/en-us/dotnet/communitytoolkit/maui/views/popup
我也有同样的问题。我忘了把.UseMauiCommunityToolkit();
加到MauiProgram.cs
。
你也可以试试这个:
var popup = new PopupPage();
await PopupExtensions.ShowPopupAsync<PopupPage>(this, popup);