WPF数据网格:如何获取单元格的内容?

7

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

所谓内容,指的是其中可能包含的一些纯文本。


我知道对于一些人来说可能很简单,但我是WPF的新手,一直在尝试像在Forms中使用DataGridView那样做一些事情,但都没有成功。因此,非常希望能得到详细的解决方案! - Partial
也许事情并不那么简单... - Partial
我想我会使用WindowsFormsIntegration帮助下的Forms中的DataGridView... - Partial
3个回答

6

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

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

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

谢谢!我知道一定有办法……比起来自Forms的DataGridView要复杂一些,但WPF不像Forms那么成熟。 - Partial
没问题。我认为Xceed(第三方)DataGrid使用DataGridView结构。 - Rob Sobers
公共自动属性: public string FirstName { get; set; } public string LastName { get; set; } - TheGeekZn

1
如果您使用 DataTable 进行绑定,可以通过行的 Item 属性获取 DataRowView。
DataRowView rowView = e.Row.Item as DataRowView;

1
通常,DataGrid 单元格的内容是数据绑定的,因此反映了在给定行中显示的对象的属性(在大多数情况下)的状态。因此,访问模型可能比访问视图更容易。
话虽如此(访问模型而不是视图),我的问题是:您想做什么?您是否正在寻找遍历可视树以查找在屏幕上呈现的控件(或控件)的方法?您希望通过行和列索引引用单元格吗?

例如,使用Forms DataGridView,您可以执行以下操作: string cellContent = dataGridView1.Rows[0].Cells[1].ToString(); - Partial
你如何使用WPF数据网格实现类似的功能? - Partial
是的,我希望能够通过行和列索引获取单元格。 - Partial
我也在寻找类似的东西。一个很好的例子是,在 DataGridView 中,你可以使用通用的复制和粘贴方式,但在 WPF DataGrid 中似乎不可能。有人知道这是否可能在 WPF DataGrid 的下一个版本中实现吗? - newman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接