Expanding Selected Item height in ListBox

前端 未结 1 1727
后悔当初
后悔当初 2021-01-20 23:53

Is there a way that I can have the SelectedItem\'s height larger than the rest of the items in a ListBox? This is what I have right now, yet it just acts as a normal listbox:

相关标签:
1条回答
  • 2021-01-21 00:39

    Your OnMeasureItem isn't doing anything while the DrawMode is OwnerDrawFixed. Change the mode to OwnerDrawVariable.

    Unfortunately, the MeasureItem event only happens when the handle gets created, so here is a work-around:

    public class BuddyListBox  : ListBox
    {
      int thisIndex = -1;
    
      public BuddyListBox()
      {
        this.DrawMode = DrawMode.OwnerDrawVariable;
      }
    
      protected override void OnDrawItem(DrawItemEventArgs e)
      {
        if (this.Items.Count > 0)
        {
          if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
            e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds);
          else
            e.Graphics.FillRectangle(SystemBrushes.Window, e.Bounds);
          e.Graphics.DrawString(this.Items[e.Index].ToString(), e.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top);
          base.OnDrawItem(e);
        }
      }
    
      protected override void OnSelectedIndexChanged(EventArgs e)
      {
        base.OnSelectedIndexChanged(e);
        thisIndex = this.SelectedIndex;
        this.RecreateHandle();
      }
    
      protected override void OnMeasureItem(MeasureItemEventArgs e)
      {
        if (e.Index > -1)
        {
          if (e.Index == thisIndex)
            e.ItemHeight = 32;
          else
            e.ItemHeight = 16;
        }
        base.OnMeasureItem(e);
      }
    }
    
    0 讨论(0)
提交回复
热议问题