选择列表框后,将对象从数据库传递到下一页

时间:2018-12-11 05:55:38

标签: c# uwp uwp-xaml

我有一个列表框,该列表框由存储在SQLite DB中的产品填充。列表框的填充方式如下:

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        string navigatedFrom;
        base.OnNavigatedTo(e);
        navigatedFrom = (string)e.Parameter;

        if (navigatedFrom == "main")
        {
            var products = new ObservableCollection<Product>(data.GetProducts().ToList());

            foreach (var product in products)
            {
                ListBox.Items.Add("Product Name: " + product.ProductName + " Price: " + product.Price + " Quantity: " + product.Quantity);
            }
        }
        else
        {

        }
    }

,列表框选择的处理方式如下:

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var product = ListBox.SelectedItem as Product;

        if (product != null)
        {
            Frame.Navigate(typeof(DetailsPage), product.Id);
        }

        ListBox.SelectedIndex = -1;
    }

从列表框中选择产品后,应用程序应导航到详细信息页面,该页面显示所选产品对象的所有详细信息。当我从列表中选择产品时,会出现我的问题,该产品对象始终为null。如何确保以正确的格式用正确的信息填充产品对象?

1 个答案:

答案 0 :(得分:0)

更改此内容:

foreach (var product in products)
{
    ListBox.Items.Add("Product Name: " + product.ProductName + " Price: " + product.Price + " Quantity: " + product.Quantity);
}

foreach (var product in products)
{
    ListBox.Items.Add(product);
}

产品类别示例:

    public class Product
    {
        public string ProductName { get; private set; }
        public string Price { get; private set; }
        public string Quantity { get; private set; }

        public override string ToString()
        {
            return $"Product Name: {this.ProductName} Price: {this.Price} Quantity: {this.Quantity}";
        }

    }