Значки в DataGridViewComboBoxColumn

У меня есть DataGridViewComboBoxColumn в моем приложении, которое определяется следующим образом

DataGridViewComboBoxColumn TransferActionCol = new DataGridViewComboBoxColumn();
TransferActionCol.DataSource = Enum.GetValues(typeof(TransferActionEnum));
TransferActionCol.DataPropertyName = "TransferAction";
TransferActionCol.Name = "Transfer Action";
TransferActionCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
fileListdataGridView.Columns.Add(TransferActionCol);

TransferActionEnum — это перечисление со значениями Download, Upload и Ignore. Все работает нормально, но я хотел бы знать, есть ли способ отобразить значок в ячейках этого столбца, а не текстовое значение перечисления? Если возможно, я хотел бы отображать значки как тогда, когда пользователь делает выбор, так и после.


person Eric Anastas    schedule 21.11.2009    source источник
comment
как насчет IValueConverter   -  person Aran Mulholland    schedule 22.11.2009


Ответы (1)


Будет ли это Ответ MSDN работает? Я оставлю перевод вам:

РЕДАКТИРОВАТЬ: версия С# доступна на исходной странице.

Private Sub Form1_Load(ByVal sender As System.Objec  t, ByVal e As System.EventArgs) Handles MyBase.Load  
    Dim cboColumn As DataGridViewComboBoxColumn  
    cboColumn = New DataGridViewComboBoxColumn  
    With cboColumn  
        .Name = "Color"  
        .Items.Add("Red")  
        .Items.Add("Blue")  
        .Items.Add("Green")  
    End With  
    Me.DataGridView1.Columns.Add(cboColumn)  
    Dim txtColumn As DataGridViewTextBoxColumn  
    txtColumn = New DataGridViewTextBoxColumn  
    With txtColumn  
        .Name = "Description"  
    End With  
    Me.DataGridView1.Columns.Add(txtColumn)  
End Sub

Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    If TypeOf e.Control Is ComboBox Then
        DirectCast(e.Control, ComboBox).DrawMode = DrawMode.OwnerDrawFixed
        Try
            RemoveHandler DirectCast(e.Control, ComboBox).DrawItem, AddressOf combobox1_DrawItem
        Catch ex As Exception

        End Try
        AddHandler DirectCast(e.Control, ComboBox).DrawItem, AddressOf combobox1_DrawItem
    End If
End Sub

Private Sub combobox1_DrawItem(ByVal sender As Object, ByVal e As System.Windows.Forms.DrawItemEventArgs)
    Dim g As Graphics = e.Graphics
    Dim s As String
    Dim br As Brush = SystemBrushes.WindowText
    Dim brBack As Brush
    Dim rDraw As Rectangle
    Dim bSelected As Boolean = CBool(e.State And DrawItemState.Selected)
    Dim bValue As Boolean = CBool(e.State And DrawItemState.ComboBoxEdit)

    rDraw = e.Bounds
    rDraw.Inflate(-1, -1)

    If bSelected And Not bValue Then
        brBack = Brushes.LightBlue
        g.FillRectangle(Brushes.LightBlue, rDraw)
        g.DrawRectangle(Pens.Blue, rDraw)
    Else
        brBack = Brushes.White
        g.FillRectangle(brBack, e.Bounds)
    End If

    br = Nothing
    brBack = Nothing
    rDraw = Nothing

    Try
        s = DirectCast(sender, ComboBox).Items.Item(e.Index).ToString
    Catch
        s = ""
    End Try

    Dim x, y As Integer

    x = e.Bounds.Left + 25
    y = e.Bounds.Top + 1
    Dim c As Color
    Dim b As SolidBrush
    c = Color.FromName(s)
    b = New SolidBrush(c)

    g.FillRectangle(b, x - 20, y + 2, 10, 10)
    g.DrawString(s, DataGridView1.Font, Brushes.Black, x, y)
End Sub
person Mohit Deshpande    schedule 24.12.2009
comment
Не очень чистый пример, однако это работает. См.: social.msdn. microsoft.com/Forums/en-US/winforms/thread/ и msdn.microsoft.com/en-us/library/ для получения дополнительной информации. Я сделал это, и это может работать. Однако просто помните, что если у вас есть несколько раскрывающихся столбцов в сетке данных, они могут использовать один и тот же элемент управления редактированием. Это может создать проблемы, если не будет обработано. - person Tony; 17.06.2010
comment
Код в ответе влияет только на открытый выпадающий список и закрытый список, который имеет фокус после выбора. При потере фокуса содержимое ячейки отображается по умолчанию (только текст). - person miroxlav; 16.07.2015