WPF DataGrid: how do you get the contents of one cell?

How do you get the contents of a single cell in a WPF DataGrid toolbox in C #?

By content, I mean simple text that may be there.

+6
c # wpf datagrid wpftoolkit
source share
3 answers

Following what Philip said, a DataGrid usually data bound. Below is an example where my WPF DataGrid bound to an ObservableCollection<PersonName> , where a PersonName consists of FirstName and LastName (both lines).

DataGrid supports automatic column creation, so the example is pretty simple. You will see that I can access the rows by their index and get the cell value in that row using the property name corresponding to the column name.

 namespace WpfApplication1 { /// <summary> /// Interaction logic for Window1.xaml /// </summary> 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<PersonName> { 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; } } } } 
+6
source share

Typically, the contents of a DataGrid cell are bound to data and therefore reflects the state of the property (in most cases) of the object that is displayed in this row. Therefore, it may be easier to access the model rather than the view.

Having said that (access model is not considered), my question is: what are you trying to do? Are you looking for ways to move the visual tree to find the control (or controls) that appears on the screen? How do you expect cell references, by columns and columns?

+1
source share

If you bind using a DataTable, you can get a DataRowView from the Row Item property.

 DataRowView rowView = e.Row.Item as DataRowView; 
+1
source share

All Articles