WPF中的datagrid点击一个单元格,怎么获取单元格里面的值

2024-12-18 21:23:07
推荐回答(2个)
回答1:

Text4.Text = DataGrid1.Text

回答2:

给段我写的Demo哈,有不理解的地方欢迎提问
前台代码:








后台代码:
public partial class BaiduKnows : Window
{
public BaiduKnows()
{
InitializeComponent();

List peoplelist = new List();
peoplelist.Add(new People() { age = 10, name = "linda" });
peoplelist.Add(new People() { age = 11, name = "tom" });
peoplelist.Add(new People() { age = 12, name = "peter" });
peoplelist.Add(new People() { age = 13, name = "mary" });

dg.ItemsSource = peoplelist;
}
class People
{
public int age { get; set; }
public string name { get; set; }
}

private void dg_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
DataGrid dg = sender as DataGrid;

People item = dg.SelectedCells[0].Item as People;

string colhead = dg.SelectedCells[0].Column.Header.ToString();

switch (colhead)
{
case "age" : txt.Text = item.age.ToString();
break;
case "name": txt.Text = item.name.ToString();
break;
}
}
}
可能有更好的做法,我这个只是提供一种思路哈!~