.NET MAUI项目始终为null。

huangapple go评论64阅读模式
英文:

.NET MAUI item is always null

问题

以下是您提供的内容的中文翻译:

XAML:

我正在使用 MAUI 开发应用程序。我有四个页面,它们几乎相同。在第四个页面上,我始终得到从视图传递的模型为 NULL。我尝试了各种方法,从创建另一个页面到复制并粘贴一个工作的页面到 XAML 和 C# 中。我知道这可能是一些简单的东西,但它一直在躲避我。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:models="clr-namespace:WhatGoesIn.Models"
             x:Class="WhatGoesIn.Views.ExportPage"
             xmlns:ios="clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls"
             ios:Page.UseSafeArea="True"
             Title="Export">
    <ContentPage.BindingContext>
        <models:ExportItem />
    </ContentPage.BindingContext>
    <ScrollView>
        <VerticalStackLayout
                             Padding="20"
                             Spacing="10"
                             VerticalOptions="StartAndExpand">
            <Label Text="Date" FontAttributes="Bold"/>
            <DatePicker Date="{Binding StartDate}" MinimumDate="01/01/2023"/>
            <Label Text="Time" FontAttributes="Bold"/>
            <DatePicker Date="{Binding ToDate}"/>
            <Label Text="Recipient" FontAttributes="Bold" FontSize="16"/>
            <Entry Text="{Binding Recipient}" />
            <Button Text="Export" Clicked="OnExportClicked" />
            <Button Text="Cancel"
                    Clicked="OnCancelClicked" />
        </VerticalStackLayout>
    </ScrollView>
</ContentPage>

C#:

我正在使用 WhatGoesIn.Models 命名空间。

namespace WhatGoesIn.Views
{
    [QueryProperty("Item", "Item")]
    public partial class ExportPage : ContentPage
    {
        WhatGoesInDatabase database;

        public ExportItem Item
        {
            get => BindingContext as ExportItem;
            set => BindingContext = value;
        }

        public ExportPage(WhatGoesInDatabase whatGoesInDatabase)
        {
            InitializeComponent();
            BindingContext = this;
            database = whatGoesInDatabase;
        }

        private async void OnExportClicked(object sender, EventArgs e)
        {
            ExportItem item = Item as ExportItem; // <= 始终为 NULL!

            string body = await database.ExportItemAsync(item);

            if (string.IsNullOrEmpty(Item.Recipient))
            {
                await DisplayAlert("No Recipient", "Please choose the recipient of the report.", "OK");
                return;
            }

            if (Email.Default.IsComposeSupported)
            {

                string subject = "What Goes In Food Log!";
                string[] recipients = new[] { Item.Recipient };

                var message = new EmailMessage
                {
                    Subject = subject,
                    Body = body,
                    BodyFormat = EmailBodyFormat.PlainText,
                    To = new List<string>(recipients)
                };

                await Email.Default.ComposeAsync(message);
            }

            await Shell.Current.GoToAsync("..");
        }

        private async void OnCancelClicked(object sender, EventArgs e)
        {
            await Shell.Current.GoToAsync("..");
        }
    }
}

模型:

我正在使用 SQLite 命名空间。

namespace WhatGoesIn.Models
{
    public class ExportItem
    {
        [PrimaryKey, AutoIncrement]
        public long ID { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime ToDate { get; set; }
        public string Recipient { get; set; }
    }
}

请注意,代码中可能包含 HTML 编码,需要根据需要进行处理。如果您有任何其他问题或需要进一步的帮助,请告诉我。

英文:

I'm developing an app using MAUI. I have four pages that are virtually identical. On the fourth, I always get NULL for the model being passed from the view. I've tried every number of things, from creating another page to copy and pasting a working page into the XAML and C#. I know it is probably something simple, but it is eluding me.

XAML

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;ContentPage xmlns=&quot;http://schemas.microsoft.com/dotnet/2021/maui&quot;
             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot;
             xmlns:models=&quot;clr-namespace:WhatGoesIn.Models&quot;
             x:Class=&quot;WhatGoesIn.Views.ExportPage&quot;
             xmlns:ios=&quot;clr-namespace:Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific;assembly=Microsoft.Maui.Controls&quot;
             ios:Page.UseSafeArea=&quot;True&quot;
             Title=&quot;Export&quot;&gt;
    &lt;ContentPage.BindingContext&gt;
        &lt;models:ExportItem /&gt;
    &lt;/ContentPage.BindingContext&gt;
    &lt;ScrollView&gt;
        &lt;VerticalStackLayout
                             Padding=&quot;20&quot;
                             Spacing=&quot;10&quot;
                             VerticalOptions=&quot;StartAndExpand&quot;&gt;
            &lt;Label Text=&quot;Date&quot; FontAttributes=&quot;Bold&quot;/&gt;
            &lt;DatePicker Date=&quot;{Binding StartDate}&quot; MinimumDate=&quot;01/01/2023&quot;/&gt;
            &lt;Label Text=&quot;Time&quot; FontAttributes=&quot;Bold&quot;/&gt;
            &lt;DatePicker Date=&quot;{Binding ToDate}&quot;/&gt;
            &lt;Label Text=&quot;Recipient&quot; FontAttributes=&quot;Bold&quot; FontSize=&quot;16&quot;/&gt;
            &lt;Entry Text=&quot;{Binding Recipient}&quot; /&gt;
            &lt;Button Text=&quot;Export&quot; Clicked=&quot;OnExportClicked&quot; /&gt;
            &lt;Button Text=&quot;Cancel&quot;
                    Clicked=&quot;OnCancelClicked&quot; /&gt;
        &lt;/VerticalStackLayout&gt;
    &lt;/ScrollView&gt;
&lt;/ContentPage&gt;

C#

using WhatGoesIn.Models;

namespace WhatGoesIn.Views;

[QueryProperty(&quot;Item&quot;, &quot;Item&quot;)]
public partial class ExportPage : ContentPage
{
    WhatGoesInDatabase database;

    public ExportItem Item
    {
        get =&gt; BindingContext as ExportItem;
        set =&gt; BindingContext = value;
    }

    public ExportPage(WhatGoesInDatabase whatGoesInDatabase)
    {
        InitializeComponent();
        BindingContext = this;
        database = whatGoesInDatabase;
    }

    private async void OnExportClicked(object sender, EventArgs e)
    {
        ExportItem item = Item as ExportItem; // &lt;= always NULL!

        string body = await database.ExportItemAsync(item);

        if (string.IsNullOrEmpty(Item.Recipient))
        {
            await DisplayAlert(&quot;No Recipient&quot;, &quot;Please choose the recipient of the report.&quot;, &quot;OK&quot;);
            return;
        }

        if (Email.Default.IsComposeSupported)
        {

            string subject = &quot;What Goes In Food Log!&quot;;
            string[] recipients = new[] { Item.Recipient };

            var message = new EmailMessage
            {
                Subject = subject,
                Body = body,
                BodyFormat = EmailBodyFormat.PlainText,
                To = new List&lt;string&gt;(recipients)
            };

            await Email.Default.ComposeAsync(message);
        }

        await Shell.Current.GoToAsync(&quot;..&quot;);
    }

    private async void OnCancelClicked(object sender, EventArgs e)
    {
        await Shell.Current.GoToAsync(&quot;..&quot;);
    }
}

Model

using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WhatGoesIn.Models
{
    public class ExportItem
    {
        [PrimaryKey, AutoIncrement]
        public long ID { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime ToDate { get; set; }
        public string Recipient { get; set; }
    }
}

答案1

得分: 2

问题似乎是Item属性未正确设置。XAML已经为ContentPage设置了BindingContext,而您尝试再次设置BindingContext。这会导致BindingContext被覆盖,Item未正确初始化。

看起来您需要从ExportPage构造函数中删除这行代码:

BindingContext = this;
英文:

It seems like the issue is that the Item property is not being set properly. The XAML is already setting the BindingContext for the ContentPage, and you are trying to set the BindingContext again. This is causing the BindingContext to be overwritten and the Item is not being initialized correctly.

Looks like you need to remove this line from the ExportPage constructor:

BindingContext = this;

huangapple
  • 本文由 发表于 2023年5月14日 05:22:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244929.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定