Silverlight DataGrid how to get cell value from selected item?

I am trying to get a cell value from a selected item in a dllagrid silverlight file. In the attached code, I can go to the properties of the cell and change its forecolor, but I can not get the value of the cell. Can someone please let me know what I'm doing wrong? Many thanks for your help!

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; } 
+4
source share
4 answers

Thanks VooDooChild, see my solution below using a text block to get the value.

 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); } } } } 
+4
source
 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" object } } 
+1
source

Have you tried something like this pseudo:

 string myString = ((MyNamespace.MyEntity)(myDataGrid.SelectedItem)).myStringProperty; 
+1
source

Source: https://habr.com/ru/post/1313912/


All Articles