2012-11-02 28 views
6

Đối với WinForms đó là:Bắt trị tế bào nào trong DataGrid trong WPF

var value = DataGridView.Rows[0].Cells[0].Value 

Có cách nào để có được nó trong WPF?

+1

Khi tôi nói với mọi nhà phát triển winforms tôi thấy hittin đầu của mình chống lại WPF ... quên tất cả mọi thứ bạn đã học được từ winforms, đây là một khung thời gian khác (IMO) tốt hơn và đòi hỏi một tư duy hoàn toàn khác. Hãy xem MVVM và làm quen với các khả năng ràng buộc WPF –

Trả lời

5

Tôi nghĩ rằng cách tốt nhất là nên sử dụng mục tài sản và truy cập trực tiếp mục dữ liệu của bạn:

var dataItem = dataGrid.Items[0] as ...; 

Nhưng Bạn có thể sử dụng lớp này để có được các tế bào và truy cập các giá trị với GetValue() phương pháp (sẽ giống như ví dụ của bạn).

Mã lấy từ đây: datagrid get cell index

static class DataGridHelper { 
    static public DataGridCell GetCell(DataGrid dg, int row, int column) { 
     DataGridRow rowContainer = GetRow(dg, row); 

     if (rowContainer != null) { 
      DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); 

      // try to get the cell but it may possibly be virtualized 
      DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      if (cell == null) { 
       // now try to bring into view and retreive the cell 
       dg.ScrollIntoView(rowContainer, dg.Columns[column]); 
       cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      } 
      return cell; 
     } 
     return null; 
    } 

    static public DataGridRow GetRow(DataGrid dg, int index) { 
     DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); 
     if (row == null) { 
      // may be virtualized, bring into view and try again 
      dg.ScrollIntoView(dg.Items[index]); 
      row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); 
     } 
     return row; 
    } 

    static T GetVisualChild<T>(Visual parent) where T : Visual { 
     T child = default(T); 
     int numVisuals = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < numVisuals; i++) { 
      Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); 
      child = v as T; 
      if (child == null) { 
       child = GetVisualChild<T>(v); 
      } 
      if (child != null) { 
       break; 
      } 
     } 
     return child; 
    } 
} 
3

Nói chung, bạn không cần phải làm điều đó. Trong WPF, datagrid có nghĩa là được sử dụng với ràng buộc dữ liệu, có nghĩa là có một bộ sưu tập hoặc đối tượng bên dưới có cùng giá trị với ô, vì vậy bạn cần truy cập trực tiếp vào bộ sưu tập/đối tượng đó. Nếu bạn cần truy cập vào giá trị ô, bạn có thể cần xem xét lại thiết kế của mình.

Các vấn đề liên quan