C# winform ,以自定义userControl作为listbox的item,drawItem的DrawFocusRectangle作用是选中某项,这一项就会框起来
但我发现一个很诡异的问题。如果form中只有listbox这一个控件,就没有问题,选中的会被框起来
但如果随便加个控件,比如下面代码中一个button,点击选中也不会有加框效果,当然,获取selectedItemIndex还是正确的
但不知道为什么会是这样的表现了
form的代码
[C#] 纯文本查看 复制代码 namespace CSharpDemo.Demo.MyItemInControl
{
public partial class MyItemInListBoxForm : Form
{
public MyItemInListBoxForm()
{
InitializeComponent();
// 此绘制模式下,才可以自己决定每项的高度
Lst.DrawMode = DrawMode.OwnerDrawVariable;
Lst.Height = (int)(new UserControlItem().Height * 2.5f);
Lst.Width = new UserControlItem().Width;
}
private void MyItemInListBoxForm_Load(object sender, EventArgs e)
{
{
UserControlItem itemControl = new UserControlItem();
itemControl.UserName = "张三";
itemControl.UserPost = "会计";
itemControl.UserPhoto = Color.Red;
Lst.Items.Add(itemControl);
}
{
UserControlItem itemControl = new UserControlItem();
itemControl.UserName = "李四";
itemControl.UserPost = "出纳";
itemControl.UserPhoto = Color.Green;
Lst.Items.Add(itemControl);
}
{
UserControlItem itemControl = new UserControlItem();
itemControl.UserName = "王五";
itemControl.UserPost = "预算";
itemControl.UserPhoto = Color.Blue;
Lst.Items.Add(itemControl);
}
{
UserControlItem itemControl = new UserControlItem();
itemControl.UserName = "赵六";
itemControl.UserPost = "经理";
itemControl.UserPhoto = Color.Yellow;
Lst.Items.Add(itemControl);
}
{
UserControlItem itemControl = new UserControlItem();
itemControl.UserName = "孙七";
itemControl.UserPost = "保安";
itemControl.UserPhoto = Color.Purple;
Lst.Items.Add(itemControl);
}
}
private void Lst_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= 0 && e.Index < Lst.Items.Count)
{
// 获取要绘制的自定义UserControl
UserControlItem control = (UserControlItem)Lst.Items[e.Index];
// 创建一个大小与自定义UserControl相同的Bitmap
Bitmap bitmap = new Bitmap(control.Width, control.Height);
// 将自定义UserControl绘制到Bitmap中
control.DrawToBitmap(bitmap, new Rectangle(0, 0, control.Width, control.Height));
// 绘制Bitmap到ComboBox中
e.Graphics.DrawImage(bitmap, e.Bounds);
// 绘制选中项获取焦点时的矩形区域
e.DrawFocusRectangle();
}
}
private void Lst_MeasureItem(object sender, MeasureItemEventArgs e)
{
// 获取要测量的自定义UserControl
UserControlItem control = (UserControlItem)Lst.Items[e.Index];
// 设置项的高度为自定义UserControl的高度
e.ItemHeight = control.Height;
}
private void BtnGetSelectedItem_Click(object sender, EventArgs e)
{
if (Lst.SelectedIndex < 0)
MessageBox.Show("没有选中任何项");
else
MessageBox.Show($"选中项的index为:{Lst.SelectedIndex},对应姓名为{(Lst.SelectedItem as UserControlItem).UserName}");
}
}
}
自定义userControl的代码
[C#] 纯文本查看 复制代码 namespace CSharpDemo.Demo.MyItemInControl
{
public partial class UserControlItem : UserControl
{
public UserControlItem()
{
InitializeComponent();
}
public string UserName
{
get { return LblName.Text; }
set { LblName.Text = value; }
}
public string UserPost
{
get { return LblPost.Text; }
set { LblPost.Text = value; }
}
public Color UserPhoto
{
get { return PicPhoto.BackColor; }
set { PicPhoto.BackColor = value; }
}
}
}
|