wpf 如何在wpf c#中将数据从datagrid显示到文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22646356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:20:14  来源:igfitidea点击:

How to display data from datagrid to textbox in wpf c#

c#wpfdatagridtextboxwpfdatagrid

提问by fkr

Can some1 please give me an example or a code, how to display data from datagrid to textbox in c# - wpf app.

请给我一个例子或代码,如何在c#中将数据从数据网格显示到文本框 - wpf app.

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();
        }

回答by BradleyDotNET

First, WPF is not WinForms, trying to code thing the same way is just going to cause you pain. What you are trying to do is actually really easy in WPF! The shortest solution is to bind directly to the DataGrid SelectedItem property:

首先,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...

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). The other way would be to bind SelectedItem and then have the other controls bind to that, like so:

现在假设 DataGrid 绑定到您的 ViewModel(不是您的代码隐藏)中的“用户”类(它绝对应该是)的集合。另一种方法是绑定 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. 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. In case you haven't done anything with MVVM, here is a great tutorial (MSDN).

当然,您现在需要在 ViewModel 中绑定一个“CurrentUser”属性。两种方式都是同样有效的方法,只需决定您更喜欢哪种方式即可。如果您需要“CurrentUser”对象用于代码中的其他内容,则第二个更好,第一个更快一点,如果您不需要它,则没有 shell 属性。如果您还没有对 MVVM 做过任何事情,这里有一个很棒的教程 ( MSDN)。