簡體   English   中英

如何在WPF C#中將數據從DataGrid顯示到文本框

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

可以給我一個例子或代碼,如何在C#-WPF應用程序中將數據從數據網格顯示到文本框。

我試圖像在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做任何事情,那么這里是一個很棒的教程( MSDN )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM