我尝试开始使用 .Net MAUI,并按照以下描述的步骤设置了我的开发环境:
我还运行了“maui-check”CLI 工具,一切都已检查完毕,但是当我使用 Visual Studio 2019 v16.11.0 Preview 2.0(在 Windows 10 Home 20H2 上运行)创建新的 .NET MAUI 应用程序时,我得到了“当前上下文中不存在名称“InitializeComponent”构建错误。它还找不到对表单上任何控件的引用,例如“当前上下文中不存在名称“CounterLabel””
我已经尝试了这篇文章中的几乎所有内容。名称“InitializeComponent”在当前上下文中不存在,其中包含添加和删除文件、进行更改以及将其改回等建议......基本上除了在许愿井中扔一分钱之外的所有内容。
我发现一个常见的错误是命名空间不匹配,但以下是我所显示的命名空间是正确的:
应用程序.xaml:
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MauiApp1"
x:Class="MauiApp1.App">
...
</Application>
Run Code Online (Sandbox Code Playgroud)
应用程序.xaml.cs
using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;
using System;
using Application = Microsoft.Maui.Controls.Application;
namespace MauiApp1
{
public partial class App : Application
{
public App()
{
InitializeComponent(); <-- This is throwing the build error...
}
protected override IWindow CreateWindow(IActivationState activationState)
{
this.On<Microsoft.Maui.Controls.PlatformConfiguration.Windows>()
.SetImageDirectory("Assets");
return new Microsoft.Maui.Controls.Window(new MainPage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
主页.xaml:
ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage"
BackgroundColor="{DynamicResource PageBackgroundColor}">
...
</ContentPage>
Run Code Online (Sandbox Code Playgroud)
MainPage.xaml.cs
using System;
using Microsoft.Maui.Controls;
namespace MauiApp1
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent(); <-- This is throwing the build error...
}
int count = 0;
private void OnCounterClicked(object sender, EventArgs e)
{
count++;
CounterLabel.Text = $"Current count: {count}"; <-- This is throwing the build error...
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
---====更新====---
我创建的项目的路径是 c:\develop\c#...... 一旦我将项目复制到不包含“c#”的文件夹,它就可以工作。这显然会导致后台的某些解析失败。
小智 60
我遇到了同样的问题,看起来当我在 VS 中创建 ContentPage 时,它仍然指向 Xamarin Forms。将命名空间更改为 MAUI 后,我将 XAML 页面的构建操作(右键单击 Xaml 页面>>属性>>BuildAction)更新为 MauiXaml,它对我有用。