如何将绑定值从列表视图传递到函数中? C# UWP

How do I pass a binded value from a listview into a function? C# UWP

我正在处理 C# UWP 作业,我有一个列表视图显示来自数据库的信息。我想显示一个订单列表,每一行都有一个 orderID 和一个删除订单的按钮(这会将它从数据库中删除)。我虽然可以使用 x:Name="orderid" 并在我的函数中提取该值,但它无法在 c# 代码中识别它。

.xaml.cs 文件包括:

   Order o = new Order();
   OrderList.ItemsSource = o.GetProducts(user);

.xaml(为了示例删除了其他列):

     <RelativePanel Grid.Row="4" Grid.RowSpan="3" Grid.Column="0" Grid.ColumnSpan="7" HorizontalAlignment="Center">
            <ListView Name="OrderList"
                  SelectionMode="Single"
                  ScrollViewer.VerticalScrollBarVisibility="Auto"
                  ScrollViewer.IsVerticalRailEnabled="True"
                  ScrollViewer.VerticalScrollMode="Enabled"
                  ScrollViewer.HorizontalScrollMode="Enabled"
                  ScrollViewer.HorizontalScrollBarVisibility="Auto"
                  ScrollViewer.IsHorizontalRailEnabled="True"
                  Margin="20">
                <ListView.HeaderTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal"  >
                            <TextBlock Text="ID" Margin="8,0" Width="50" Foreground="DarkRed" />
                            <TextBlock Text="Date" Width="200" Foreground="DarkRed" />
                            <TextBlock Text="Delete" Width="50"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.HeaderTemplate>
                <ListView.ItemTemplate>
                    <DataTemplate x:DataType="local:Order">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock x:Name="orderid"
                                    Text="{x:Bind OrderID}"
                                    Width="50" />
                            <TextBlock Name="orderdate"
                                    Text="{x:Bind OrderDate}"
                                    Width="200" />                           
                            <Button Content="X" Click="Button_Click"/>
                        </StackPanel>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </RelativePanel>

C#(Order Class - OrderID 等都是属性):

public ObservableCollection<Order> GetProducts(User user)
        {

            const string GetOrdersQuery = "select * from orders";

            var orders = new ObservableCollection<Order>();
            try
            {
                
                using (SqlConnection conn = new SqlConnection(user.ConnectionString))
                {
                    conn.Open();
                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        using (SqlCommand cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = GetOrdersQuery;
                            using (SqlDataReader reader = cmd.ExecuteReader()) 
                            {
                                while (reader.Read())
                                {
                                    var order = new Order();
                                    order.OrderID = (int)reader["orderID"];
                                    order.OrderDate = (DateTime)reader["orderDate"];
                                    order.MethodOfDelivery = (string)reader["methodOfDelivery"];
                                    order.DeliveryAddress = (reader["deliveryAddress"] as string);
                                    order.MethodOfPayment = (string)reader["methodOfPayment"];
                                    order.CardUsed = (reader["cardNumber"] as string);
                                    order.Subtotal = (decimal)reader["subtotal"];
                                    order.Discount = (decimal)reader["discountPercentage"];
                                    order.Tax = (decimal)reader["tax"];
                                    order.OrderTotal = (decimal)reader["orderTotal"];

                                    order.CustID = (reader["custID"] as int?) ?? 0;


                                    orders.Add(order);

                                }
                            }
                        }
                    }
                }
                return orders;
            }
            catch (Exception eSql)
            {
                Debug.WriteLine("Exception: " + eSql.Message);
            }
            return null;
        }

然后我想在 xaml.cs 文件中创建一个函数来获取该行的 orderID,并进行查询以根据 ID 删除订单,但是 orderid.Text 不会'由于某些原因不能在这里工作。

任何 suggestions/help 将不胜感激! 如果我的代码有点乱,那是因为我对此还很陌生!

一种可能的解决方案是将“OrderId”绑定到 Button 元素中的“Tag”属性。

 <Button Content="X" Click="Button_Click" Tag="{Binding Id}"/>

绑定后,在您的 Click 事件处理程序中调用一个方法将其从数据库和 ObservableCollection 中删除,类似于:

    private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        var button = sender as Button;
        _viewModel.DeleteOrder((int)button.Tag);
    }

我的 DeleteOrder 方法很简单:

private ObservableCollection<Order> _orders;
public ObservableCollection<Order> Orders
{
    get { return _orders; }
    set { _orders = value; OnChange(); }
}

public void DeleteOrder(int id)
{
    var order = Orders.FirstOrDefault(o => o.Id == id);
    if (order != null)
    {
        Orders.Remove(order);
    }
}