我正在使用毛伊岛开发一款应用程序.我有四页几乎一模一样的书.在第四个示例中,对于从视图传递的模型,我总是得到NULL.我try 了各种方法,从创建另一个页面到复制,再到将工作页面粘贴到XAML和C #中.我知道这可能是一件简单的事情,但它让我难以理解.
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:models="clr-namespace:WhatGoesIn.型号s"
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 #
using WhatGoesIn.型号s;
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; // <= always 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("..");
}
}
型号
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WhatGoesIn.型号s
{
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; }
}
}