如何在C#中获取WPF工具包DataGrid的单个单元格内容?
所谓内容,指的是其中可能包含的一些纯文本。
如何在C#中获取WPF工具包DataGrid的单个单元格内容?
所谓内容,指的是其中可能包含的一些纯文本。
根据Phillip所说,DataGrid
通常是数据绑定的。下面是一个示例,其中我的WPF DataGrid
被绑定到一个ObservableCollection<PersonName>
,其中PersonName
由FirstName
和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; }
}
}
}
DataRowView rowView = e.Row.Item as DataRowView;