WPF DataGrid:你如何获得单个单元格的内容?

如何在C#中获取WPF工具包DataGrid的单个单元格的内容?

根据内容,我的意思是可以在那里的一些纯文本。

按照Phillip的说法 – DataGrid通常是数据绑定的。 下面是我的WPF DataGrid绑定到ObservableCollection的示例,其中PersonNameFirstNameLastName (两个字符串)组成。

DataGrid支持自动创建列,因此示例非常简单。 您将看到我可以通过索引访问行,并使用与列名对应的属性名称获取该行中单元格的值。

 namespace WpfApplication1 { ///  /// Interaction logic for Window1.xaml ///  public partial class Window1 : Window { public Window1() { InitializeComponent(); // Create a new collection of 4 names. NameList n = new NameList(); // Bind the grid to the list of names. dataGrid1.ItemsSource = n; // Get the first person by its row index. PersonName firstPerson = (PersonName) dataGrid1.Items.GetItemAt(0); // Access the columns using property names. Debug.WriteLine(firstPerson.FirstName); } } public class NameList : ObservableCollection { public NameList() : base() { Add(new PersonName("Willa", "Cather")); Add(new PersonName("Isak", "Dinesen")); Add(new PersonName("Victor", "Hugo")); Add(new PersonName("Jules", "Verne")); } } public class PersonName { private string firstName; private string lastName; public PersonName(string first, string last) { this.firstName = first; this.lastName = last; } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } } } 

通常,DataGrid单元格的内容是数据绑定的,因此反映了在给定行中显示的对象的属性(在大多数情况下)的状态。 因此,访问模型而不是视图可能更容易。

话虽如此(访问模型没有查看)我的问题是:你想做什么? 您是否正在寻找遍历可视树以查找屏幕上呈现的控件(或控件)的方法? 您希望如何通过行和列索引引用单元格?

如果使用DataTable进行绑定,则可以从Row的Item属性中获取DataRowView。

 DataRowView rowView = e.Row.Item as DataRowView;