如何获取单个单元格的内容

如何获取单个单元格的内容

本文介绍了WPF DataGrid:如何获取单个单元格的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

按内容我的意思是一些可能在那里的纯文本。 / p>

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

推荐答案

以下是Phillip所说的 - DataGrid 通常是数据绑定的。下面是一个例子,其中我的WPF DataGrid 绑定到一个 ObservableCollection< PersonName> 其中一个 PersonName FirstName LastName (两个字符串)组成。

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).

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

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; }
        }
    }
}

这篇关于WPF DataGrid:如何获取单个单元格的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 13:40