我有以下应用程序,其中有一个从SQLite数据库填充的CollectionView,但我在单击时很难将选定的值从CollectionView传递到另一个页面。
Records.cs
using SQLite;
namespace b_records.Models
{
[Table("records)")]
public class Record
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(250)]
public string Amount { get; set; }
}
}
AppShell.xaml.cs
namespace b_records;
public partial class AppShell : Shell
{
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute("DetailPage", typeof(DetailPage));
}
}
MainPage.xaml
<CollectionView x:Name="recordList" Grid.Row="5" SelectionChanged="OnCollectionViewSelectionChanged" SelectionMode="Single">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Label Text="{Binding Id}" />
<Label Grid.Column="1" Text="{Binding Amount}" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
MainPage.xaml.cs
private async void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
{
int id = (e.CurrentSelection.FirstOrDefault() as Record).Id;
await Shell.Current.GoToAsync($"DetailPage?id={id}");
}
DetailPage.xaml.cs
namespace b_records;
[QueryProperty(nameof(id), "id")]
public partial class DetailPage : ContentPage
{
public int id { get; set; }
public DetailPage()
{
InitializeComponent();
lblText.Text = id.ToString();
}
}
请尝试按照Microsoft文档中的详细信息进行操作,网址为:https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-6.0#pass-data
但是每次我单击CollectionView时,我都会被带到DetailPage,并且lblText.text中的值是0,而不是从SQLite数据库填充的CollectionView中行的id值。
知道为什么吗?
2条答案
按热度按时间qnzebej01#
构造函数是在创建任何对象时调用的第一件事。(直接在数据成员上初始化值可能例外。)此时尚未设置任何属性值。因此,尚未设置
id
。一种解决方案是将需要任何查询值的任何代码移到OnAppearing的覆盖中:
另一种解决方案是将该行移到属性setter中:
zbwhf8kr2#
是的,在获取传递的值
id
之前调用了页DetailPage
的构造函数。因此,您可以尝试以下代码: