2016-04-02 18 views
0

Im tıklandığında çizilmiş öğeyi alın. Öğeleri çizmek kolaydı, hangi öğenin tıklandığını bulmak zor kısımdı, 2 saat boyunca bunu anlamaya çalışıyordum. Kimsenin hangi öğeye tıklandığını nasıl öğrenebilirim? İşte benim kodi tüm öğeleri çizmek özel bir öğe listesi oluşturma

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; 
      } 
     } 
    } 
} 
+0

[bu cevaba] göz (http://stackoverflow.com/questions/32919918/how-to-draw-line-and-select-it-in-panel/32920894?s=1|1.0572#32920894) - O hatları için yazılıdır; Dikdörtgenler için şeyler, Contains yöntemini kullanan olay simples'idir. Ama bir List üzerinden gidiyor temel fikir hasta her öğeye bir Nokta özelliği eklemek zorunda olduğunu kullanmak için aynı – TaW

+0

olduğunu, ben bunu yapamam. – Adrao

+0

Gerçekten değil. Line sınıfını kullanmayın; Sadece Öğelerinizle çalışan bir şey yazın. Dikdörtgenlerle daha da basit olmalı ..! – TaW

cevap

1

Rectangle güzel yöntemlerden bir çift sahiptir. Bir Contains(Point) geçerli:

protected override void OnClick(EventArgs e) 
    { 
     // Get the clicked item 
     int ItemYPosition = 0; 
     foreach (string Item in Items) 
     { 
      Rectangle ItemRectangle = new Rectangle(0, ItemYPosition, 
                this.Width, _ItemHeight); 

      if (ItemRectangle.Contains(e.Location)) // found one hit! 

      ItemYPosition += _ItemHeight; 
     } 
    } 

Size bir hit hatta sen bir vuruşta daha bulabilir eğer bulunca ne yapacağına karar için size kalmış ..

+0

Teşekkürler, çok iyi çalışıyor! – Adrao

İlgili konular