You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# UWP:将数据从一个ListView通过数组传递至下一页的另一个ListView

Hey Mike, let's work through getting those selected DATA items from your main page's ListView over to the checkout page's ListView. Here are a few straightforward, reliable approaches tailored to your code structure:

Approach 1: Pass Selected Items via Page Constructor

This is the simplest method for basic navigation scenarios.

  1. In your main page, grab the selected items and pass them when navigating to the checkout page:
// Assuming your main ListView is named "MainListView"
var selectedItems = MainListView.SelectedItems.Cast<DATA>().ToList();

// Navigate to checkout page and pass the selected items
await Navigation.PushAsync(new CheckoutPage(selectedItems));
  1. In your checkout page, modify the constructor to accept the list and bind it to your checkout ListView:
public partial class CheckoutPage : ContentPage
{
    public CheckoutPage(List<DATA> checkoutItems)
    {
        InitializeComponent();
        
        // Bind the received items to your checkout ListView (named "CheckoutListView")
        CheckoutListView.ItemsSource = checkoutItems;
    }
}

This keeps your code decoupled and works better for larger apps, especially if you need to access the cart items across multiple pages.

  1. Create a shared CartViewModel:
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

public class CartViewModel : INotifyPropertyChanged
{
    private List<DATA> _cartItems = new List<DATA>();
    public List<DATA> CartItems
    {
        get => _cartItems;
        set
        {
            _cartItems = value;
            OnPropertyChanged();
        }
    }

    public void AddItems(List<DATA> items)
    {
        CartItems.AddRange(items);
        OnPropertyChanged(nameof(CartItems));
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
  1. Register the CartViewModel as a singleton (in your App.xaml.cs):
public App()
{
    InitializeComponent();
    // Register the CartViewModel so it's accessible across pages
    DependencyService.RegisterSingleton<CartViewModel>(new CartViewModel());
    MainPage = new NavigationPage(new MainPage());
}
  1. In your main page, add selected items to the cart when the user triggers checkout:
var cartViewModel = DependencyService.Get<CartViewModel>();
var selectedItems = MainListView.SelectedItems.Cast<DATA>().ToList();
cartViewModel.AddItems(selectedItems);

// Navigate to checkout page
await Navigation.PushAsync(new CheckoutPage());
  1. Bind the checkout page's ListView to the CartViewModel:
    • First, create a CheckoutPageViewModel:
    public class CheckoutPageViewModel
    {
        public CartViewModel CartViewModel { get; }
    
        public CheckoutPageViewModel()
        {
            CartViewModel = DependencyService.Get<CartViewModel>();
        }
    }
    
    • Update your CheckoutPage code-behind:
    public partial class CheckoutPage : ContentPage
    {
        public CheckoutPage()
        {
            InitializeComponent();
            BindingContext = new CheckoutPageViewModel();
        }
    }
    
    • Update your checkout page XAML to bind the ListView:
    <ListView x:Name="CheckoutListView" ItemsSource="{Binding CartViewModel.CartItems}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Padding="10">
                        <Label Text="{Binding Distinguisher}" FontSize="Headline" />
                        <Label Text="{Binding Price, StringFormat='${0:F2}'}" FontSize="Subtitle" />
                        <Label Text="{Binding Description}" FontSize="Body" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    

Approach 3: Use WeakReferenceMessenger (For Loosely Coupled Scenarios)

This is great if you don't want to pass data directly or use a shared ViewModel, and works well in .NET MAUI/Xamarin.Forms.

  1. Define a message class:
public class CartUpdatedMessage
{
    public List<DATA> SelectedItems { get; set; }
}
  1. Send the message from your main page:
var selectedItems = MainListView.SelectedItems.Cast<DATA>().ToList();
WeakReferenceMessenger.Default.Send(new CartUpdatedMessage { SelectedItems = selectedItems });

await Navigation.PushAsync(new CheckoutPage());
  1. Receive the message in your checkout page:
using CommunityToolkit.Mvvm.Messaging;

public partial class CheckoutPage : ContentPage
{
    public CheckoutPage()
    {
        InitializeComponent();
        
        // Register to receive the cart update message
        WeakReferenceMessenger.Default.Register<CartUpdatedMessage>(this, (recipient, message) =>
        {
            CheckoutListView.ItemsSource = message.SelectedItems;
        });
    }

    // Unregister to prevent memory leaks when the page is dismissed
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        WeakReferenceMessenger.Default.Unregister<CartUpdatedMessage>(this);
    }
}

Quick Note: Ensure Multi-Selection is Enabled

Don't forget to set your main ListView's SelectionMode to Multiple if you want users to select more than one item:

<ListView x:Name="MainListView" SelectionMode="Multiple">
    <!-- Your item template here -->
</ListView>

内容的提问来源于stack exchange,提问作者Mike M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:19:04