c# - WPF 数据网格 : How do you get the content of a single cell?

标签 c# wpf datagrid wpftoolkit

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

我所说的内容是指可能包含在其中的一些纯文本。

最佳答案

按照菲利普所说的 - DataGrid通常是数据绑定(bind)的。下面是我的 WPF DataGrid 的示例绑定(bind)到 ObservableCollection<PersonName>其中一个 PersonNameFirstName 组成和 LastName (两个字符串)。

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

关于c# - WPF 数据网格 : How do you get the content of a single cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1295843/

相关文章:

c# - 关于C#自动实现属性的问题

c# - pdb(程序调试数据库)的用途是什么?

c# - 多线程环境中的任务列表 - "enumeration operation may not execute"

wpf - 在带有 .NET 6 运行时的 Windows 10 上启动 WPF 应用程序不起作用

wpf datagrid 数据绑定(bind)与嵌套对象(如主细节)

c# - 处理 float / double 的微小变化

WPF Documentviewerbase.Print。删除对话框

c# - 使用 C# 绑定(bind)到 WPF 中的 UserControl

c# - 如何将 WPF DataGrid 绑定(bind)到可变数量的列?

datagrid - Material-UI DataGrid : How do I add a tooltip to each row cell?