首页 > 解决方案 > 使用自动生成的列在 WPF DataGrid 上显示图像

问题描述

我将图像存储在 MySQL 数据库中,最近我正在从 win 表单迁移到 VB WPF。

我已经阅读了有关此问题的问题,我不满意。自动生成列时,如何设置列以显示图像而不是字节数组。

列名将未指定,列索引未指定。

如果我必须使用模板,有人可以给我一个明确的解释,它会怎么样?

请不要将我指向其他链接,因为我没有找到对我有用的答案。

任何帮助都感激不尽

我的网格上的额外信息:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition />
            <RowDefinition Height="40" />
        </Grid.RowDefinitions>
        <Grid Grid.Row="1" Margin="0">
            <DataGrid
                x:Name="DataGrid1"
                Grid.Column="0"
                AutoGenerateColumns="True"
                IsReadOnly="True"
                ItemsSource="{Binding}"
                SelectionMode="Extended"
                SelectionUnit="Cell" />
        </Grid>
    </Grid>

标签: wpfvb.net

解决方案


我希望这个答案对某人有所帮助,而无需使用转换器等

基本上,通过处理 autogeneratingcolumn 事件,您可以设置和格式化该值。假设数据库上的所有字节数组都是图像,否则应该实现额外的条件(列名等)。

Private Sub DataGrid1_AutoGeneratingColumn(sender As Object, e As DataGridAutoGeneratingColumnEventArgs) Handles DataGrid1.AutoGeneratingColumn
        Dim column As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
        If e.PropertyType = GetType(System.Byte()) Then
            Try
                Dim img As New FrameworkElementFactory(GetType(Image))
                img.SetBinding(Image.SourceProperty, New Binding(e.PropertyName))
                e.Column = New DataGridTemplateColumn With {
                    .CellTemplate = New DataTemplate() With {
                        .VisualTree = img
                    },
                    .Header = ""}
            Catch ex As Exception
            End Try
        End If
        If e.PropertyType = GetType(System.DateTime) Then
            column.Binding.StringFormat = "dd/MM/yyyy hh:mm"
        End If
        If e.PropertyType = GetType(System.UInt32) Or e.PropertyType = GetType(System.Decimal) Then
            column.Binding.StringFormat = "#,###0"
        End If
    End Sub

推荐阅读