温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - WPF DataGrid Get Cell Content from DataGridTemplateColumn

c# - WPF DataGrid从DataGridTemplateColumn获取单元格内容

发布于 2020-03-27 11:09:40

我有一个绑定到dataGrid的dataTable:

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>

我可以通过选择像这样的行来获取ID(DataGridTextColumn)的单元格值:

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

但是,当我想要获取规格(作为文本)或图像(作为图像)时,它说“ ...返回null”。可能是由于DataGridTemplateColumn导致的。如何从DataGridTemplateColumn内部获取价值?(特别是,我需要获取图像并设置一个图像(称为imgPopup),就像dataGrid图像单元格一样)

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?

查看更多

查看更多

提问者
E.Ak
被浏览
50
E.Ak 2019-07-04 05:17

我找到了解决方案我编辑了代码,它的工作原理是:

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;

发布
问题

分享
好友

手机
浏览

扫码手机浏览