我正在用MAUI开发一个应用程序。我有四页几乎完全相同。在第四个问题上,我总是为从视图传递的模型获得NULL。我尝试了各种方法,从创建另一个页面到将工作页面复制并粘贴到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.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#
using 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; // <= 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.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条答案
按热度按时间cu6pst1q1#
问题似乎是
Item
属性没有正确设置。XAML已经为ContentPage
设置了BindingContext
,而您正在尝试再次设置BindingContext
。这导致BindingContext
被覆盖,并且Item
未正确初始化。看起来你需要从
ExportPage
构造函数中删除这一行: