Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在wpf c中显示从datagrid到textbox的数据#_C#_Wpf_Datagrid_Textbox_Wpfdatagrid - Fatal编程技术网

C# 如何在wpf c中显示从datagrid到textbox的数据#

C# 如何在wpf c中显示从datagrid到textbox的数据#,c#,wpf,datagrid,textbox,wpfdatagrid,C#,Wpf,Datagrid,Textbox,Wpfdatagrid,请给我一个例子或代码,如何在c#-wpf应用程序中显示从datagrid到textbox的数据 我曾尝试在Windows窗体应用程序中这样做,但代码不起作用 if (e.RowIndex >= 0) { DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex]; name.Text = row.Cells["Name"].Value.ToString();

请给我一个例子或代码,如何在c#-wpf应用程序中显示从datagrid到textbox的数据

我曾尝试在Windows窗体应用程序中这样做,但代码不起作用

if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

            name.Text = row.Cells["Name"].Value.ToString();
            lastName.Text = row.Cells["LastName"].Value.ToString();
            userName.Text = row.Cells["UserName"].Value.ToString();
            password.Text = row.Cells["Password"].Value.ToString();
        }

首先,WPF不是WinForms,试图以同样的方式编写代码只会给您带来痛苦。在WPF中,您要做的实际上非常简单!最短的解决方案是直接绑定到DataGrid SelectedItem属性:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}">
...
</DataGrid>

<TextBox Text="{Binding ElementName=UserGrid, Path=SelectedItem.Name}"/>
...More of the same...

...
…更多相同的。。。
现在,假设DataGrid绑定到ViewModel(而不是您的代码隐藏)中的“User”类集合(它绝对应该是)。另一种方法是绑定SelectedItem,然后让其他控件绑定到该控件,如下所示:

<DataGrid x:Name="UserGrid" ItemsSource="{Binding Users}" SelectedItem="{Binding CurrentUser}">
...
</DataGrid>

<TextBox Text="{Binding Path=CurrentUser.Name}"/>
...More of the same...

...
…更多相同的。。。

当然,现在需要在ViewModel中绑定一个“CurrentUser”属性。两种方法都是同样有效的方法,只要决定你更喜欢哪一种。如果代码中的其他内容需要“CurrentUser”对象,则第二个更好,第一个更快,如果不需要,则没有shell属性。如果您还没有使用MVVM,那么这里有一个很棒的教程()。

@HamletHakobyan我已经更新了post@HamletHakobyan没什么,因为我不知道怎么做:还有问题吗?我有10个文本框,只有7个显示数据…我一定是做错了什么。哪一个数据是Path=SelectedItem.Name…在哪里可以找到“Name”名称?好的,太好了!如果你遇到别的事情,请告诉我。对于遇到此问题的任何其他人,快速回答是,“SelectedItem.Name”表示查看“ElementName”中命名的元素的“SelectedItem”对象,然后获取其“Name”属性。非常感谢,谢谢你抽出时间!报答