简体   繁体   English

如何在 WPF 中获取所选 ListView 行的值

[英]How do I get the value of the selected ListView row in WPF

I have filled a ListView with data coming from a database.我已经用来自数据库的数据填充了 ListView。

I now want to be able to delete a selected listview item out of the database.我现在希望能够从数据库中删除选定的列表视图项。 For the query, I need to get the value of the ID column but I can't find how to do it.对于查询,我需要获取 ID 列的值,但我找不到如何去做。

在此处输入图像描述

This approach has been working for me (the GetSelectedItem method):这种方法一直对我有用( GetSelectedItem方法):

MainWindow.xaml主窗口.xaml

<Window
    x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    mc:Ignorable="d">

    <Grid>
        <ListView x:Name="listViewItems" ItemsSource="{Binding Items}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

        <Button
            x:Name="btnGetSelectedItem"
            HorizontalAlignment="Right"
            VerticalAlignment="Bottom"
            Click="btnGetSelectedItem_Click"
            Content="Get selected item" />
    </Grid>
</Window>

MainWindow.xaml.cs主窗口.xaml.cs

public partial class MainWindow : Window
{
    public List<Item> Items { get; } = new List<Item>
    {
        new Item("Reginald"),
        new Item("Gregor"),
        new Item("Howard")
    };

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private Item? GetSelectedItem()
    {
        //check if the current SelectedItem is a valid Item
        if (listViewItems.SelectedItem is not Item item)
        {
            //if not -> return null
            return null;
        }

        //if yes, return the valid item
        return item;
    }

    private void btnGetSelectedItem_Click(object sender, RoutedEventArgs e)
    {
        var item = GetSelectedItem();
        Console.WriteLine($"Selected item: {item?.Name ?? "none"}");
    }
}

Item.cs物品.cs

public class Item
{
    public string Name { get; set; }

    public Item(string name)
    {
        Name = name;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM