C# WPF是否在单击按钮时传递选定的列表视图项信息?

63lcw9qa  于 2023-08-07  发布在  C#
关注(0)|答案(1)|浏览(129)

我想先说一句,我才刚刚开始学习WPF。
我在我的学习项目中创建了一个小窗口,现在我试图找出最好的方法,将所选对象信息从ListView传递到按钮点击时发生的事件(在本例中,Remove)。
窗口看起来像这样:

Xaml是这样的:`

<Grid>
    <Button Content="Add" HorizontalAlignment="Right" Margin="0,10,10,0" VerticalAlignment="Top" Width="50" Height="25" Click="Button_Click_Add"/>
    <Button Content="Edit" HorizontalAlignment="Right" Margin="0,40,10,0" VerticalAlignment="Top" Width="50" Height="25" Click="Button_Click_Edit"/>
    <Button Content="Remove" HorizontalAlignment="Right" Margin="0,100,10,0" VerticalAlignment="Top" Width="50" Height="25" Click="Button_Click_Remove"/>
    <Button Content="Refresh" HorizontalAlignment="Right" Margin="0,70,10,0" VerticalAlignment="Top" Width="50" Height="25" Click="Button_Click_Refresh"/>
    <ListView Name="lvEmployeeList" Margin="10,10,65,10">
        <ListView.View>
            <GridView>
                <GridViewColumn Width="150" Header="First Name" DisplayMemberBinding="{Binding FirstName}" />
                <GridViewColumn Width="150" Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
                <GridViewColumn Width="150" Header="Position" DisplayMemberBinding="{Binding Position}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

字符串
以及MainWindow类的相关信息:

public MainWindow()
    {
        InitializeComponent();

        EmployeeList employeeList = EmployeeList.Load();
        lvEmployeeList.ItemsSource = employeeList.employeeRecord;

    }

    private void Button_Click_Add(object sender, RoutedEventArgs e)
    {
        var newWindow = new UserInfo();
        newWindow.Show();
    }
    private void Button_Click_Edit(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("You have chosen to Edit");
    }
    private void Button_Click_Remove(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Removing");
    }
    private void Button_Click_Refresh(object sender, RoutedEventArgs e)
    {
        EmployeeList employeeList = EmployeeList.Load();
        lvEmployeeList.ItemsSource = employeeList.employeeRecord;
        MessageBox.Show("Attempting a Refresh");
    }
}`


其中很多都是占位符函数,所以我最终可以真正处理数据。每个对象都有一个名字,姓氏,位置和后面的隐藏ID。我的计划是以某种方式获取对象ID并将其用于remove函数,但我不确定如何从ListView中的选定对象中获取该ID,然后仅在特定按钮单击事件中使用该ID。

iqxoj9l9

iqxoj9l91#

我假设你有一个Employee类,如下所示:

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Position { get; set; }
}

字符串
然后,您可以使用以下代码来获取Employee Id:

private void Button_Click_Remove(object sender, RoutedEventArgs e)
{
    Employee selectedEmployee = (Employee)lvEmployeeList.SelectedItem;
    int employeeId = selectedEmployee.Id;
}

相关问题