编程语言
首页 > 编程语言> > 将DataGrid的行传递给另一个WPF表单C#

将DataGrid的行传递给另一个WPF表单C#

作者:互联网

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

我试图将所选行的每个单元格的每个值传递给另一种形式,但我不知道如何使用wpf做到这一点.

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

如何解决这个问题呢 ?

谢谢

解决方法:

看起来您正在为DataGrid使用数据集.

>使用绑定获取选定的行(SelectedItem).
>发送此ChosenItem作为对其他表单/窗口的引用.
>将此发送的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;
}

标签:wpfdatagrid,wpf,c
来源: https://codeday.me/bug/20191119/2033538.html