您的位置:首页 > 编程语言 > C#

C#中ListBox和ListView的透明及内容居中效果实现

2017-06-19 21:23 399 查看
作为一个C#的初学者,本文的技术参考多篇博客和论坛的内容,具体来自哪里也不甚了了,在此多谢这些大神。

以下代码是ListBox的透明及内容居中效果实现,ListView可依此同样实现。

class TransparentListBox : ListBox
{
private Boolean isAllignCenter;
public TransparentListBox(Boolean center)
{
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.BorderStyle = System.Windows.Forms.BorderStyle.None;
//this.MultiSelect = false;
isAllignCenter = center;
}

protected override void OnSelectedIndexChanged(EventArgs e)
{
this.Invalidate();
base.OnSelectedIndexChanged(e);
}

protected override void OnPaint(PaintEventArgs e)
{
System.Drawing.StringFormat strFmt = new System.Drawing.StringFormat(System.Drawing.StringFormatFlags.NoClip);
strFmt.Alignment = System.Drawing.StringAlignment.Center;

if (this.Focused && this.SelectedItem != null)
{
Rectangle itemRect = this.GetItemRectangle(this.SelectedIndex);
e.Graphics.FillRectangle(Brushes.LightBlue, itemRect);
}
for (int i = 0; i < Items.Count; i++)
{
if (isAllignCenter == true)
{
e.Graphics.DrawString(this.GetItemText(this.Items[i]), this.Font,
new SolidBrush(this.ForeColor), this.GetItemRectangle(i), strFmt);
}
else
{
e.Graphics.DrawString(this.GetItemText(this.Items[i]), this.Font,
new SolidBrush(this.ForeColor), this.GetItemRectangle(i));
}

}
base.OnPaint(e);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息