简体   繁体   English

如何在WPF C#中将数据从DataGrid显示到文本框

[英]How to display data from datagrid to textbox in wpf c#

Can some1 please give me an example or a code, how to display data from datagrid to textbox in c# - wpf app. 可以给我一个例子或代码,如何在C#-WPF应用程序中将数据从数据网格显示到文本框。

I've tried to do it like in Windows Forms application, but the code doesn't work. 我试图像在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();
        }

First, WPF is not WinForms, trying to code thing the same way is just going to cause you pain. 首先,WPF不是WinForms,尝试以相同的方式编写代码只会引起您的痛苦。 What you are trying to do is actually really easy in WPF! 在WPF中,您实际上想做的事很简单! The shortest solution is to bind directly to the DataGrid SelectedItem property: 最短的解决方案是直接绑定到DataGrid SelectedItem属性:

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

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

Now this assumes that the DataGrid is bound to a collection of the "User" class (which it absolutely should be) in your ViewModel (NOT your code-behind). 现在,假设DataGrid绑定到ViewModel中的“ User”类的集合(它绝对应该是)(而不是隐藏代码)。 The other way would be to bind SelectedItem and then have the other controls bind to that, like so: 另一种方法是绑定SelectedItem,然后将其他控件绑定到该控件,如下所示:

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

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

Of course you now need a "CurrentUser" property in your ViewModel to bind to. 当然,现在您需要在ViewModel中绑定一个“ CurrentUser”属性。 Both ways are equally valid approaches, just decide which you like better. 两种方法都是同等有效的方法,只需确定您更喜欢哪种方法即可。 The second is better if you need the "CurrentUser" object for something else in code, the first is a bit quicker and doesn't have the shell property if you don't need it. 如果您需要将“ CurrentUser”对象用于代码中的其他内容,则第二种方法会更好,第一种方法会更快一些,如果不需要,则不具有shell属性。 In case you haven't done anything with MVVM, here is a great tutorial ( MSDN ). 如果您没有对MVVM做任何事情,那么这里是一个很棒的教程( MSDN )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM