I have a DataGrid with some columns. One of them is a Template Column. That TemplateColumn is declared as shown below :
<DataGridTemplateColumn Header="First Name">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding FirstName}" Loaded="TextBox_Loaded_1"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
Requirements :
Get the text inside the TextBlock that resides inside CellTemplate in a generic way.
What I have tried :
When I press Enter on TemplateColumn's cell, I want the Text inside TextBlock. So, I have used the PreviewKeyDown Event of DataGrid as follows :
private void DataGrid_PreviewKeyDown(.............)
{
If(e.Key == Key.Enter)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
if(dep != null && dep is DataGridCell)
{
var CellTemplate = ((DataGridCell)dep).Content; //gives me ContentPresenter instead of Textblock
if (CellTemplate is TextBlock)
{
if (((TextBlock)CellTemplate).Text.Trim() == "")
{
//Do whatever I want
}
}
}
}
}
The code described above returns a ContentPresenter instead of TextBlock. Why this happens?
Also, Content of the ContentPresenter is null.