我有一个绑定到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?
答案 0 :(得分:1)
DataGridTemplateColumn只是为DataGrid上的列定义模板样式,您永远不要在此元素上定义绑定,绑定应该在数据级别完成。
答案 1 :(得分:0)
我找到了solution。 我编辑了代码,它起作用了:
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;