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

Xamarin Forms实现ListView选中订单的详情展示技术问询

Hey there! It looks like you're setting up a ListView with context actions to view order details in your Xamarin.Forms app. Let me help you complete that implementation and share some best practices along the way.


Completed XAML Code

First, here's the full, corrected XAML for your user_page ListView—including a complete context action set and a basic layout to display order details:

<ListView x:Name="Wash_list" ItemsSource="{Binding Orders}" SelectionMode="None">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <!-- Layout to display core order info -->
                <StackLayout Padding="15,10" Orientation="Vertical">
                    <Label Text="{Binding OrderNumber}" FontSize="Headline" />
                    <Label Text="{Binding OrderDate, StringFormat='Ordered: {0:MM/dd/yyyy HH:mm}'}" FontSize="Subtitle" />
                    <Label Text="{Binding Status}" FontSize="Caption" TextColor="{Binding StatusColor}" />
                </StackLayout>
                
                <!-- Context menu actions -->
                <ViewCell.ContextActions>
                    <MenuItem Clicked="OnMoreInfoClicked" CommandParameter="{Binding .}" 
                              Text="More Info" IconImageSource="info_icon.png" />
                    <MenuItem Clicked="OnCancelOrderClicked" CommandParameter="{Binding .}" 
                              Text="Cancel" TextColor="Red" IconImageSource="cancel_icon.png" />
                </ViewCell.ContextActions>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Code-Behind Implementation

Next, let's add the code to handle these actions and load your order data. First, define a simple Order model to represent your order data:

public class Order
{
    public int OrderNumber { get; set; }
    public DateTime OrderDate { get; set; }
    public string Status { get; set; }
    public Color StatusColor { get; set; }
    // Add other properties like Total, Items, CustomerName, etc.
}

Then, in your user_page.xaml.cs file:

using System.Collections.ObjectModel;
using Xamarin.Forms;

public partial class UserPage : ContentPage
{
    // ObservableCollection auto-updates the ListView when data changes
    public ObservableCollection<Order> Orders { get; set; }

    public UserPage()
    {
        InitializeComponent();
        Orders = new ObservableCollection<Order>();
        LoadLatestOrders();
        BindingContext = this;
    }

    // Replace this with your actual data fetch logic (API/database)
    private void LoadLatestOrders()
    {
        Orders.Add(new Order 
        { 
            OrderNumber = 12345, 
            OrderDate = DateTime.Now.AddDays(-1), 
            Status = "Completed", 
            StatusColor = Color.Green 
        });
        Orders.Add(new Order 
        { 
            OrderNumber = 12346, 
            OrderDate = DateTime.Now.AddHours(-6), 
            Status = "In Progress", 
            StatusColor = Color.Orange 
        });
    }

    // Handle "More Info" click to navigate to details page
    private async void OnMoreInfoClicked(object sender, EventArgs e)
    {
        var menuItem = sender as MenuItem;
        var selectedOrder = menuItem.CommandParameter as Order;

        if (selectedOrder != null)
        {
            // Navigate to your order details page, passing the selected order
            await Navigation.PushAsync(new OrderDetailsPage(selectedOrder));
        }
    }

    // Optional: Handle "Cancel" order action
    private async void OnCancelOrderClicked(object sender, EventArgs e)
    {
        var menuItem = sender as MenuItem;
        var selectedOrder = menuItem.CommandParameter as Order;

        if (selectedOrder != null && selectedOrder.Status != "Completed")
        {
            var confirm = await DisplayAlert("Cancel Order", 
                $"Are you sure you want to cancel order #{selectedOrder.OrderNumber}?", 
                "Yes", "No");
            
            if (confirm)
            {
                // Add your cancel logic here (API call, database update)
                Orders.Remove(selectedOrder);
                await DisplayAlert("Success", "Order cancelled successfully!", "OK");
            }
        }
    }
}

If you're using the MVVM pattern (best practice for Xamarin.Forms), replace event handlers with commands. Here's how that would look in your ViewModel:

using System.Windows.Input;
using Xamarin.Forms;

public class UserViewModel : BaseViewModel // Assume BaseViewModel implements INotifyPropertyChanged
{
    public ObservableCollection<Order> Orders { get; set; }
    public ICommand MoreInfoCommand { get; }
    public ICommand CancelOrderCommand { get; }

    private readonly INavigation _navigation;

    public UserViewModel(INavigation navigation)
    {
        _navigation = navigation;
        Orders = new ObservableCollection<Order>();
        MoreInfoCommand = new Command<Order>(async (order) => await NavigateToDetails(order));
        CancelOrderCommand = new Command<Order>(async (order) => await CancelOrder(order));
        LoadLatestOrders();
    }

    private async Task NavigateToDetails(Order order)
    {
        await _navigation.PushAsync(new OrderDetailsPage(order));
    }

    private async Task CancelOrder(Order order)
    {
        // Add cancel logic here
    }

    private void LoadLatestOrders()
    {
        // Populate orders as before
    }
}

Then update your XAML to bind to the commands instead of using Clicked events:

<MenuItem Command="{Binding MoreInfoCommand}" CommandParameter="{Binding .}" Text="More Info" />
<MenuItem Command="{Binding CancelOrderCommand}" CommandParameter="{Binding .}" Text="Cancel" TextColor="Red" />

Bonus: Tap Entire Cell for Details

If you want users to tap the whole list item (not just the menu) to view details, set SelectionMode="Single" and add an ItemSelected handler:

<ListView x:Name="Wash_list" ItemsSource="{Binding Orders}" SelectionMode="Single" ItemSelected="OnOrderSelected">

And the handler:

private async void OnOrderSelected(object sender, SelectedItemChangedEventArgs e)
{
    var selectedOrder = e.SelectedItem as Order;
    if (selectedOrder != null)
    {
        await Navigation.PushAsync(new OrderDetailsPage(selectedOrder));
        // Deselect the item after navigation
        ((ListView)sender).SelectedItem = null;
    }
}

内容的提问来源于stack exchange,提问作者Giacomo El Ghisa Zidarich

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:54:03