wpf,在不知道DataGrid绑定类型的基础上,如何获得DataGrid上显示的值。
在用DataGrid.ItemsSource绑定类型时,DataGrid会显示相应的值,但当我不知道绑定的类型时,如何获得DataGrid上显示的值?...
在用DataGrid.ItemsSource绑定类型时,DataGrid会显示相应的值,
但当我不知道绑定的类型时,如何获得DataGrid上显示的值? 展开
但当我不知道绑定的类型时,如何获得DataGrid上显示的值? 展开
展开全部
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Items = new ObservableCollection<C>();
Items.Add(new C("a1","b1"));
Items.Add(new C("a2", "b2"));
Items.Add(new C("a3", "b3"));
DataContext = this;
}
public ObservableCollection<C> Items
{ get; set; }
//不建议这样做,但是确实可以实现
private void button1_Click(object sender, RoutedEventArgs e)
{
//获取0,0的显示的内容,前提是单元格列是DataGridTextColumn
DataGridCell c = DataGridHelper.GetCell(dataGrid1, 0, 0);
TextBlock tb=c.Content as TextBlock;
MessageBox.Show(tb.Text);
}
}
public class C
{
public C(string a, string b)
{
A = a;
B = b;
}
public string A { get; set; }
public string B { get; set; }
}
static class DataGridHelper
{
static public DataGridCell GetCell(DataGrid dg, int row, int column)
{
DataGridRow rowContainer = GR(dg, row);
if (rowContainer != null)
{
DataGridCellsPresenter p = GC<DataGridCellsPresenter>(rowContainer);
DataGridCell cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
dg.ScrollIntoView(rowContainer, dg.Columns[column]);
cell = (DataGridCell)p.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
static public DataGridRow GR(DataGrid dg, int index)
{
DataGridRow r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
if (r == null)
{
dg.ScrollIntoView(dg.Items[index]);
r = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
}
return r;
}
static T GC<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GC<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
}
展开全部
获取 dataGrid.CurrentItem.GetType(),然后使用反射 System.Reflection
下面用字符串做个示例
var data = "abcdefghijklmnopqrstuvwxyz";
var type = data.GetType();
foreach (var pi in type.GetProperties())
{
// 获取属性参数数组
var parms = pi.GetIndexParameters();
// 判断是否为数组类型的属性 ( parms > 0)
if (parms.Length == 0)
{
Console.WriteLine("{0},{1},{2}",
pi.Name, pi.PropertyType, pi.GetValue(data, null));
}
else
{
var names = parms.Select(s => s.Name).ToArray();
Console.WriteLine("{0},{1},{2}",
pi.Name, pi.PropertyType, string.Join(",", names));
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询