簡體   English   中英

從 WPF 數據網格中的當前選定行獲取值的最佳方法是什么?

[英]What is the best way to get values from the currently selected row in a WPF datagrid?

我們最近決定在 WPF 中重新創建我們的 Winforms 應用程序。 在 Winforms 中,我得到當前行的值,如下所示:

Dim supplier As String = tbl_outstandingpos.CurrentRow.Cells("Supplier").Value

在 WPF 到目前為止我能找到的最好方法是

DataRowView row = dataGrid.SelectedItem as DataRowView;
MessageBox.Show(row.Row.ItemArray[1].ToString());

這對我不起作用,因為我不想按索引而是按名稱獲取列。

我已經閱讀了很多關於 MVVM 的內容,但我仍然沒有看到給出我正在尋找的結果。

我希望用戶 select 一行,然后有標簽/文本塊填充了該行中的值(其中一些位於 DataGrid 中的隱藏列中)

我將 C# 用於新應用程序,我們將 VB 用於 winforms 之一。

鑒於DataGrid.ItemsSource是一個DataTableSelectedItem將是一個DataRowView實例。 您可以使用適當的索引器屬性按列名訪問選定的行:

C#

// Get the value of the selected row's 'LastName' column
var columnValue = (this.MyDataGrid.SelectedItem as DataRowView)["LastName"];
this.MyTextBlock.Text = columnValue;

XAML

<DataGrid x:Name="DataGrid" 
          ItemsSource="{Binding DataTable}" />

<!-- A TextBlock to display the content of the selected rows 'LastName'  column -->
<TextBlock x:Name="MyTextBlock" 
           Text="{Binding ElementName=DataGrid, Path=SelectedItem[LastName]}"/>

您可以考慮將DataRowView類型的專用SelectedRow屬性添加到您的視圖 model,而不是讓您的控件直接綁定到DataGrid.SelectedItem屬性。

暫無
暫無

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

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