WPF 将数据从数据网格绑定到文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12741514/
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 05:40:06  来源:igfitidea点击:

WPF binding data from datagrid to textbox

c#wpfwpf-controlswpfdatagrid

提问by Alfred Angkasa

i'm new to WPF and still learn on it. I create a sample application and connect to the database. After i select data to the database, i can show it into my datagrid. Now, my concern is i want to bind to textbox depends on the row from my datagrid.

我是 WPF 的新手,仍然在学习。我创建了一个示例应用程序并连接到数据库。在我选择数据到数据库后,我可以将它显示到我的数据网格中。现在,我担心的是我想绑定到文本框取决于我的数据网格中的行。

so, whenever i click or select row in my datagrid, i bind the value to textbox. i already do some google and tried. but still failed. is there any solution? thanks.

因此,每当我在数据网格中单击或选择行时,我都会将该值绑定到文本框。我已经做了一些谷歌并尝试过。但还是失败了。有什么解决办法吗?谢谢。

here is my application picture. enter image description here

这是我的应用程序图片。 在此处输入图片说明

how is the xaml look like to bind for example row no 3 to my textbox? is there any class i should implement? because in windows form i just need to call cellclick. thanks.

xaml 看起来如何将例如第 3 行绑定到我的文本框?有没有我应该实现的类?因为在 Windows 窗体中,我只需要调用 cellclick。谢谢。

回答by doerig

I'm always binding SelectedItem (datagrid Property) to a Property in my ViewModel. And then you can bind the Controls to this property. You also can achieve this without a viewmodel only with xaml:

我总是将 SelectedItem(数据网格属性)绑定到我的 ViewModel 中的一个属性。然后您可以将控件绑定到此属性。您也可以仅使用 xaml 在没有视图模型的情况下实现此目的:

<StackPanel>
    <TextBox Text="{Binding SelectedItem.Name, ElementName=myDataGrid}"/>
    <DataGrid x:Name="myDataGrid" />
</StackPanel>