Hi,
Saying you have a data grid and a button on your main page:
<Grid x:Name="LayoutRoot" Background="White" >
<sdk:DataGrid Name="dg" SelectionChanged="DgSelectionChanged" Width="200" Height="200"/>
<Button Content="Start" Click="ButtonClick" Width="200" Height="20" Margin="12,24,188,256" />
</Grid>
Event for loading some data when button is clicked:
private void ButtonClick(object sender, RoutedEventArgs e)
{
var persons = new List<Person>
{
new Person {Name = "Name 1", Address = "Address 1"},
new Person {Name = "Name 2", Address = "Address 2"}
};
dg.AutoGenerateColumns = true;
dg.ItemsSource = persons;
dg.SelectionMode = DataGridSelectionMode.Single;
}
Where person:
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
}
And when selection changes fire the following event that will do the job you need:
private void DgSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var dataGrid = sender as DataGrid;
if (dataGrid != null)
{
int selectedIndex = dataGrid.SelectedIndex;
if (selectedIndex > -1)
{
DataGridColumn column = dataGrid.Columns[0];
FrameworkElement fe = column.GetCellContent(dataGrid.SelectedItem);
FrameworkElement result = GetParent(fe, typeof(DataGridCell));
if (result != null)
{
var cell = (DataGridCell)result;
//changes the forecolor
cell.Foreground = new SolidColorBrush(Colors.Blue);
//how to get cell value?
var block = fe as TextBlock;
if (block != null)
{
string cellText = block.Text;
MessageBox.Show(cellText);
}
}
}
}
}
private FrameworkElement GetParent(FrameworkElement child, Type targetType)
{
object parent = child.Parent;
if (parent != null)
{
if (parent.GetType() == targetType)
{
return (FrameworkElement)parent;
}
return GetParent((FrameworkElement)parent, targetType);
}
return null;
}
Let me know if this helped you.