双击WPF时从窗口2向主窗口传递值

vngu2lb8  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(105)

我有2个窗口,主窗口有一个按钮,打开窗口2.
Windows 2包含保存值列表的数据网格,用户双击以从列表中选择一行,然后关闭Windows 2,并使用所选行的数据填充一些文本框
我有一些示例代码:

public class User {
    public string FirstName {get; set;}
    public string LastName { get; set;}
}
private void Button_Click(object sender, KeyEventArgs e) {
    Window2 window = new(DataToRetrieve);
    window.ShowDialog();
    
    //Get data here to and print in the text boxes
    //textbox.Text = itemRetrieved.Something;

}

使用MouseDoubleClick事件从数据网格中抓取项的方法

private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
  if (sender != null)
  {
    DataGrid grid = sender as DataGrid;
    if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
    {
       DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
       DataRowView dr = (DataRowView)dgr.Item;
    }
  }
}

如何能够发送到我的主窗口的列表中的数据选择到我的主窗口?

ukdjmx9f

ukdjmx9f1#

例如,您可以在存储选定数据的第二个窗口中添加属性,例如:

public DataRowView SelectedData { get; private set; }

private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    if (sender != null)
    {
        DataGrid grid = sender as DataGrid;
        if (grid != null && grid.SelectedItems != null && grid.SelectedItems.Count == 1)
        {
            DataGridRow dgr = grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem) as DataGridRow;
            this.SelectedData = (DataRowView)dgr.Item;
        }
    }
}

然后你只需要在MainWindow中使用这个属性:

private void Button_Click(object sender, KeyEventArgs e) 
{
    Window2 window = new(DataToRetrieve);
    window2.ShowDialog();

    // Get data here...
    textbox.Text = window2.SelectedData["someColumn"].ToString();

}

相关问题