Adding an image to a WPF DataGrid
我无法在 DataGrid (WPF) 中显示图像...有什么想法吗?
在 WinForms DataGridView 中太容易了 - 叹息
数据表
1 2 3 4 5 6 7 8 9 10 | Dim DGV As CustomControl.DGVx = ImagesItemsGrid.FindName("ImagesItems_DGV") Dim DS As DataSet = e.Result Dim DT As DataTable = DS.Tables(0).Copy Dim vDT As New DataTable With vDT.Columns .Add("ID", GetType(Integer)) .Add("Name", GetType(String)) .Add("Description", GetType(String)) .Add("Image", GetType(Image)) End With |
图像
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Dim vImageHeight As Integer = 0 For Each Row As DataRow In DT.Rows With vDT.Rows Dim ImageData As Byte() = DirectCast(Row("Image_Icon"), Byte()) Dim vImage As New Image Dim vBitMap As New BitmapImage Using vStream As New IO.MemoryStream(ImageData) vImage.Source = BitmapFrame.Create(vStream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad) End Using vImage.Height = 20 .Add(Row("Image_ID"), Row("Image_Name"), Row("Image_Description"), vImage) End With Next DT.Dispose() |
列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | For Each Col As DataColumn In vDT.Columns Dim vDataType As String = Col.DataType.ToString Select Case vDataType Case"System.Int32" DGV.Columns.Add(New DataGridTextColumn With {.Header = Col.ColumnName, .Binding = New Binding(String.Format("[{0}]", Col.ColumnName))}) Case"System.Windows.Controls.Image" Dim ImageCol As New DataGridTemplateColumn ImageCol.Header = Col.ColumnName Dim vFactory As New FrameworkElementFactory(GetType(Image)) Dim vBinding As New Binding(String.Format("[{0}]", Col.ColumnName)) vBinding.Mode = BindingMode.OneWay vFactory.SetValue(Image.SourceProperty, vBinding) Dim vCellTemplate As New DataTemplate vCellTemplate.VisualTree = vFactory ImageCol.CellTemplate = vCellTemplate DGV.Columns.Add(ImageCol) Case Else Dim DGTC As New DataGridTextColumn With DGTC .Header = Col.ColumnName .Binding = New Binding(String.Format("[{0}]", Col.ColumnName)) End With DGV.Columns.Add(DGTC) End Select Next |
数据
1 2 3 | DS.Dispose() DGV.DataContext = vDT DGV.ItemsSource = vDT.DefaultView |
文本数据按应有的方式显示,但是,尽管该列存在,但图像没有...
原来答案就是将"图像"保留为 Byte()
现在可以了
1 2 3 4 5 6 7 8 9 10 | Case"System.Byte[]" Dim ImageTemp As New DataTemplate Dim ImageCol As New DataGridTemplateColumn Dim vFactory As New FrameworkElementFactory(GetType(Image)) Dim vBinding As New Binding(Col.ColumnName) vFactory.SetBinding(Image.SourceProperty, vBinding) ImageTemp.VisualTree = vFactory ImageCol.CellTemplate = ImageTemp DGV.Columns.Add(ImageCol) |