【问题标题】:List with remove/delete button带有删除/删除按钮的列表
【发布时间】:2023-03-24 03:05:01
【问题描述】:

我正在开发一个 WinForms 应用程序,我想要一个 ListBox(或提供字符串列表的控件),这样当用户将鼠标悬停在某个项目上时,它将显示该特定项目的删除标志。

是否有任何控件可供 WinForms 执行此操作?

【问题讨论】:

  • 您应该查看第三方组件供应商,例如 Infragistics、Developer Express、Telerik 等。或者,也许您可​​以编写自己的代码。我们在这里为您提供帮助:)

标签: winforms listbox listbox-control


【解决方案1】:

将 ListBox DrawMode 设置为 OwnerDrawFixed(或 OwnerDrawVariable),您可以自己使用鼠标事件来处理:

Public Class Form1

  Private _MouseIndex As Integer = -1

  Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
    ListBox1.Items.Add("String #1")
    ListBox1.Items.Add("String #2")
  End Sub

  Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem
    e.DrawBackground()

    If e.Index > -1 Then
      Dim brush As Brush = SystemBrushes.WindowText
      If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
        brush = SystemBrushes.HighlightText
      End If
      e.Graphics.DrawString(ListBox1.Items(e.Index), e.Font, brush, e.Bounds.Left + 20, e.Bounds.Top)

      If e.Index = _MouseIndex Then
        e.Graphics.DrawString("X", e.Font, brush, e.Bounds.Left + 2, e.Bounds.Top)
      End If
    End If

  End Sub

  Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseDown
    If _MouseIndex > -1 AndAlso ListBox1.IndexFromPoint(e.Location) = _MouseIndex AndAlso e.Location.X < 20 Then
      Dim index As Integer = _MouseIndex
      If MessageBox.Show("Do you want to delete this item?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
        ListBox1.Items.RemoveAt(index)
        ListBox1.Invalidate()
      End If
    End If
  End Sub

  Private Sub ListBox1_MouseLeave(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox1.MouseLeave
    If _MouseIndex <> -1 Then
      _MouseIndex = -1
      ListBox1.Invalidate()
    End If
  End Sub

  Private Sub ListBox1_MouseMove(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseMove
    Dim index As Integer = ListBox1.IndexFromPoint(e.Location)

    If index <> _MouseIndex Then
      _MouseIndex = index
      ListBox1.Invalidate()
    End If
  End Sub

End Class

根据需要重构。

【讨论】:

  • 感谢您的回复。此代码完美运行。但我想显示一个关闭符号来指示用户。我该怎么做?
  • @Bandish 上面的代码在鼠标悬停的行项目上显示了一个“X”。代替 DrawString,您可以使用 DrawImage 并显示“X”图像。不知道您所说的“显示关闭符号”是什么意思。
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 2018-02-16
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多