WPF DataGrid: How do you get the content of a sing

2019-02-17 09:16发布

问题:

How do you get the content of a single cell of a WPF toolkit DataGrid in C#?

By content I mean some plain text that could be in there.

回答1:

Following what Phillip said - the DataGrid is usually data-bound. Below is an example where my WPF DataGrid is bound to an ObservableCollection<PersonName> where a PersonName is comprised of a FirstName and LastName (both strings).

The DataGrid supports automatic column creation so the example is quite simple. You'll see that I can access rows by their index and get the value of a cell in that row by using the property name that corresponds 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; }
        }
    }
}


回答2:

Normally, the content of a DataGrid cell is data-bound, and therefore reflect the state of a property (in most cases) of an object which is being displayed in a given row. Hence it might be easier to access the model rather than the view.

Having said that (access model not view) my question is: what are you trying to do? Are you looking of ways to traverse the visual tree to find the control (or controls) that is rendered on screen? How do you expect to reference the cell, by row and column index?



回答3:

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

DataRowView rowView = e.Row.Item as DataRowView;