【发布时间】:2016-04-03 03:21:28
【问题描述】:
我正在创建一个自定义项目列表,我在其中绘制所有项目。绘制项目很容易,找出点击了哪个项目是困难的部分,过去 2 小时我一直在努力弄清楚。有谁知道我怎样才能找出点击了哪个项目? 这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace WindowsFormsApplication2
{
class MyList : Control
{
#region Constructor
public MyList()
{
this.SetStyle(ControlStyles.UserPaint, true);
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
}
#endregion
#region Properties
private string[] Items = new string[] { "Item 1", "Item 2", "Item 3", "Item 4" };
private int _ItemHeight = 25;
public int ItemHeight
{
get { return _ItemHeight; }
set { _ItemHeight = value; this.Invalidate(); }
}
#endregion
#region Mouse Events
protected override void OnClick(EventArgs e)
{
// Get the clicked item
}
#endregion
protected override void OnPaint(PaintEventArgs e)
{
int ItemYPosition = 0;
foreach (string Item in Items)
{
Rectangle ItemRectangle = new Rectangle(0, ItemYPosition, this.Width, _ItemHeight);
e.Graphics.DrawRectangle(Pens.Red, ItemRectangle);
ItemYPosition += _ItemHeight;
}
}
}
}
【问题讨论】:
-
看看at this answer - 它是为线条而写的;对于矩形,事物是使用 Contains 方法的事件简单。但是遍历 List
的基本思想是一样的 -
要使用它,我必须为每个项目添加一个 Point 属性,我不能这样做。
-
并非如此。不要使用 Line 类;只需写一些适用于您的项目的东西。使用矩形应该更简单..!