首页 > 解决方案 > WPF C#:如何从 ListView 中的选定行获取 ID 以通过事件处理程序打开唯一窗口?

问题描述

我创建了一个带有“activemeassurements”表的 mysql 数据库。我在其中运行一个查询,BatchesVm.cs该查询输出具有最新日期且具有唯一批次 ID 的行<ListView>in MainWindow.xaml.cs。每当我双击它时,我希望能够在另一个窗口中以更详细的方式显示所选项目。绑定工作正常,并且已连接到正确的数据库。但是,我一直在努力寻找一种方法来检索 < 中所选行的 ID 以ListView>在下一个窗口中使用。这是我第一次使用 wpf。

XAML:

<Window x:Class="P5_WPF.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:P5_WPF" xmlns:local1="clr-namespace:P5_WPF.ViewModels"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="8*"/>
        <ColumnDefinition Width="3*"/>
    </Grid.ColumnDefinitions>
    <ListView ItemsSource="{Binding allBatches}" x:Name="batcheslist"  Margin="72,100,59,63" Grid.ColumnSpan="2" SelectedItem="{Binding Path=BatchID}" >
        <ListView.View>
            <GridView>
                <GridViewColumn DisplayMemberBinding="{Binding Path=batchid" Header="batch ID" />
                <GridViewColumn DisplayMemberBinding="{Binding Path=Temp}" Header="Latest temp meassurements"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Path=Humidity}" Header="Latest humidity meassurements" />
                    <GridViewColumn DisplayMemberBinding="{Binding Path=date}" Header="Date" Width="150"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
    </Window>

MainWindow.xaml.cs:

 public partial class MainWindow : Window
    {
        public MainWindow()
        {

            InitializeComponent();
            DataContext = new BatchesVm();
        }
        private void batchesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //I want to open single batch window with the id from the selected item.

            SingleBatch_Window single = new SingleBatch_Window();
            single.Show();
        }
    }

我的BatchesVm.csC# 文件包含 ListView 的 ItemsSource:

public class BatchesVm
    {
        public DataView allBatches { get; private set; }
        public BatchesVm()
        {
            var CS = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            DataTable dt = new DataTable();
            try
            {
                using (MySqlConnection connection = new MySqlConnection(CS))
                {
                    string CmdString = "select batchid,Temp,Humidity,date from (select batchid,Temp,Humidity,date,row_number() over(partition by batchid order by date desc) as rn from aktivemeassurements) t where t.rn = 1;";
                    MySqlDataAdapter adapter = new MySqlDataAdapter();
                    adapter.SelectCommand = new MySqlCommand(CmdString, connection);
                    adapter.Fill(dt);
                }
                allBatches = dt.DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot establish connection");
                MessageBox.Show(ex.Message);
            }
        }
    }

- 我如何能:

==================================================== =======================

标签: c#mysqlwpflistvieweventhandler

解决方案


For anyone wondering the same heres the solution: Through @Jdweng's help I figured out how to retrieve ID from the DataView allBatches.

From MainWindow.xaml.cs

private void batchesList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //get index of the selected row.
                int itemindex = batcheslist.Items.IndexOf(batcheslist.SelectedItems[0]);
                BatchesVm a = new BatchesVm();
                //get id of selected row.
                int batchId = a.allBatchIds[itemindex];

                SingleBatch_Window single = new SingleBatch_Window(batchId);
                single.Show();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Please choose a Batch.");
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }  
        }

ViewModel:

//Dataview of the selected sql table from query
            allBatches = dt.DefaultView;

            //converting DataView allBatches to a generic list.
            allBatchIds = allBatches.ToTable().Rows.OfType<DataRow>()
                .Select(dr => dr.Field<int>("BatchID")).ToList();

推荐阅读