我正在尝试从silverlight数据网格的选定项目中获取单元格值。在附加的代码中,我可以获得单元格的属性并更改其前景色,但我无法获得单元格的值。有人可以让我知道我做错了什么吗?非常感谢您的帮助!
private void FindDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
int selectedIndex = dataGrid.SelectedIndex;
if (selectedIndex > -1)
{
FindResult findResult = (FindResult)FindDetailsDataGrid.SelectedItem;
DataGridColumn column = dataGrid.Columns[0];
FrameworkElement fe = column.GetCellContent(dataGrid.SelectedItem);
FrameworkElement result = GetParent(fe, typeof(DataGridCell));
if (result != null)
{
DataGridCell cell = (DataGridCell)result;
//changes the forecolor
cell.Foreground = new SolidColorBrush(Colors.Blue);
//how to get cell value?
}
}
}
private FrameworkElement GetParent(FrameworkElement child, Type targetType)
{
object parent = child.Parent;
if (parent != null)
{
if (parent.GetType() == targetType)
{
return (FrameworkElement)parent;
}
else
{
return GetParent((FrameworkElement)parent, targetType);
}
}
return null;
}
答案 0 :(得分:4)
感谢VooDooChild,请参阅下面的解决方案,使用文本块获取值。
private void FindDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
int selectedIndex = dataGrid.SelectedIndex;
if (selectedIndex > -1)
{
FindResult findResult = (FindResult)FindDetailsDataGrid.SelectedItem;
DataGridColumn column = dataGrid.Columns[0];
FrameworkElement fe = column.GetCellContent(dataGrid.SelectedItem);
FrameworkElement result = GetParent(fe, typeof(DataGridCell));
if (result != null)
{
DataGridCell cell = (DataGridCell)result;
//changes the forecolor
cell.Foreground = new SolidColorBrush(Colors.Blue);
//how to get cell value?
TextBlock block = fe as TextBlock;
if (block != null)
{
string cellText = block.Text;
MessageBox.Show(cellText);
}
}
}
}
答案 1 :(得分:1)
private void FindDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid dataGrid = sender as DataGrid;
var item = dataGrid.SelectedItem;
if (item != null)
{
//in here you can get the properties with the "item"'s object
}
}
答案 2 :(得分:1)
你有没有试过像这样的伪:
string myString = ((MyNamespace.MyEntity)(myDataGrid.SelectedItem)).myStringProperty;
答案 3 :(得分:0)