将 DataGrid 的一行传递给另一个 wpf 表单 c#

Pass a Row of a DataGrid to another wpf form c#

我有一个 wpf 表单 DataGrid 和另一个 wpf 表单 TextBoxes.

我正在尝试将所选行的每个单元格的每个值传递给另一个表单,但我不知道如何使用 wpf 执行此操作。

在 wpf Form2 中,我想将这些值放入 TextBox 进行编辑,然后更新 Form1 的行,因此连接的 DataSet.

如何解决这个问题?

谢谢

您的 DataGrid 似乎使用了 DataSet

  1. 使用 Binding 获取选定的行 (SelectedItem)。

  2. 将此 ChosenItem 作为 ref 发送给另一个 form/window。

  3. 将此发送ChosenItem设置为表格网格的DataContext

现在,当您更改 Form2 中的值时,更改将反映回 form1。

例如代码,

表格 1

   <Grid>
        <DataGrid x:Name="Dgrid" HorizontalAlignment="Left" Margin="10,31,0,0" VerticalAlignment="Top" SelectedItem="{Binding ChosenItem}" />            
        <Button Content="Edit" HorizontalAlignment="Left" Margin="10,4,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
    </Grid>

Form1 代码隐藏

public partial class MainWindow : Window
{
    DataStore ds = new DataStore();

    public MainWindow()
    {
        InitializeComponent();

        Dgrid.DataContext = ds;
        Dgrid.ItemsSource = ds.DataSource.Tables[0].DefaultView;
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        DataRowView item = ds.ChosenItem;
        Window1 w = new Window1(ref item); // send selected row as ref to other form
        w.Show();
    }
}

   public class DataStore
   {
        public DataRowView ChosenItem { get; set; }

        public DataStore()
        {
            DataTable table1 = new DataTable();
            table1.Columns.Add(new DataColumn("Name", typeof(string)));
            table1.Columns.Add(new DataColumn("Address", typeof(string)));

            DataRow row = table1.NewRow();
            row["Name"] = "Name1";
            row["Address"] = "203 A";
            table1.Rows.Add(row);

            row = table1.NewRow();
            row["Name"] = "Deepak";
            row["Address"] = "BHEL Bhopal";
            table1.Rows.Add(row);

            ds.Tables.Add(table1);
        }

        DataSet ds = new DataSet();
        public DataSet DataSource { get { return ds; } }
    }

表格2

        <Grid x:Name="FormGrid" DataContext="{Binding SelectedItem, ElementName=Dgrid}">
            <TextBox HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="120"/>
            <TextBox HorizontalAlignment="Left" Height="23" Margin="0,49,0,0" TextWrapping="Wrap" Text="{Binding Address}" VerticalAlignment="Top" Width="120"/>
            <Button Content="Button" HorizontalAlignment="Left" Margin="0,100,0,0" VerticalAlignment="Top" Width="75"/>
        </Grid>

Form2 代码隐藏

public Window1(ref DataRowView item)
{
    InitializeComponent();
    FormGrid.DataContext = item;
}