C#设置Listbox的的行间距ItemHeight

       在使用Listbox的时候,ItemHeight的默认值是12,当在属性窗口里更改它时,改了又变回去了。

       这是因为Listbox默认是不能更改ItemHeight的。想要更改的话,需要这样做:

      首先设置DrawMode属性为OwnerDrawVariable,自己画Listbox。

      然后处理DrawItem和MeasureItem两个事件,DrawItem是在显示项时触发,MeasureItem是在要计算项的宽高时触发。在DrawItem里重新绘制项目,如下:

1:属性位置如下:(属性可以不用修改,直接在代码里修改)



2:代码如下:

        private void GroupRangeTips_Load(object sender, EventArgs e)
        {
            this.ListBoxGroupRange.DrawMode = DrawMode.OwnerDrawVariable;
            this.ListBoxGroupRange.DrawItem += new DrawItemEventHandler(ListBoxGroupRange_DrawItem);
        }

        //自绘Item,使其视觉效果更好
        private void ListBoxGroupRange_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
            if (e.Index >= 0)
            {
                StringFormat sStringFormat = new StringFormat();
                sStringFormat.LineAlignment = StringAlignment.Center;
                e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sStringFormat);
            }
            e.DrawFocusRectangle();
        }

        private void ListBoxGroupRange_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            e.ItemHeight = e.ItemHeight + 12;
        }



  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C#中,可以使用多种方法设置ListBox的行数。以下是三种常用的方法: 方法1:添加记录后,选择最后一条记录,让滚动条滚动到底部,再自动取消选择: ```csharp listBox1.Items.Add("a good day"); listBox1.SelectedIndex = listBox1.Items.Count - 1; listBox1.SelectedIndex = -1; //取消选择行 ``` 方法2:通过计算显示行数,设置TopIndex属性,实现滚动目的: ```csharp listBox1.Items.Add("a good day"); listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight); ``` 方法3:先计算滚动条是否在底部,然后添加记录,根据需要确定是否自动滚动: ```csharp bool scroll = false; if (listBox1.TopIndex == listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight)) scroll = true; listBox1.Items.Add("a good day"); if (scroll) listBox1.TopIndex = listBox1.Items.Count - (listBox1.Height / listBox1.ItemHeight); ``` 以上是三种常用的方法,你可以根据需要选择其中一种来设置ListBox的行数。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [C# ListBox自动滚动方法](https://blog.csdn.net/qq_27474555/article/details/132141212)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值