Warm tip: This article is reproduced from stackoverflow.com, please click
c# wpf

WPF DataGrid Get Cell Content from DataGridTemplateColumn

发布于 2020-03-27 10:22:46

I have a dataTable binding to dataGrid:

CS:

SQLiteDataAdapter sQLiteDataAdapter = new SQLiteDataAdapter(_command);
DataTable dataTable = new DataTable("Inventory");
sQLiteDataAdapter.Fill(dataTable);
for (int i = 0; i < dataTable.Rows.Count; i++)
{
    dgridTenderInventory.Items.Add(new
      {
         ID = dataTable.Rows[i]["id"],                            
         Specs = dataTable.Rows[i]["specs"],
         Image = dataTable.Rows[i]["image"]                            
       });
}

XAML:

 <DataGrid x:Name="dgridTenderInventory" RowHeaderWidth="0"  MouseDown="DgridTenderInventory_MouseDown">
    <DataGrid.Columns>
       <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
       <DataGridTemplateColumn Header="Image">
           <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image Height="50" Source="{Binding Image, Converter={StaticResource BinaryImageConverter}}"/>
                </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
       <DataGridTemplateColumn Header="Specs">
           <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Specs}" TextWrapping="Wrap"/>
                </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
     </DataGrid.Columns>
  </DataGrid>

I can get cell value for ID (DataGridTextColumn) by selecting row like this:

object item = dgridTenderInventory.SelectedItem;
string ID = dgridTenderInventory.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;

But when I want get Specs (as text) or Image (as image), it says '...returned null'. Probably it results from DataGridTemplateColumn. How can I get value from inside of a DataGridTemplateColumn? (Especially, I need to get image and set an image (called imgPopup) just like dataGrid image cell)

string specs= dgridTenderInventory.SelectedCells[2].Column.GetCellContent(item) as TextBlock).Text; // return null
imgPopup.Source = dgridTenderInventory.SelectedCells[1].Column.GetCellContent(item) as Image).Source ; // ?? how does it be implemented?
Questioner
E.Ak
Viewed
143
E.Ak 2019-07-04 05:17

I found a solution. I edited code and it works:

string specs = (VisualTreeHelper.GetChild(dgridTenderInventory.Columns[2].GetCellContent(item), 0) as TextBlock).Text;
imgPopup.Source = (VisualTreeHelper.GetChild(dgridTenderInventory.Columns[1].GetCellContent(item), 0) as Image).Source;