无法在C#中创建用户控件

时间:2016-02-28 02:20:41

标签: c# .net winforms user-controls panel

我在C#中创建用户控件但我无法弄清楚如何处理事件。我想在鼠标悬停时更改面板的backcolor属性,但它不起作用。

代码:

public partial class QuestionList : UserControl
{
    public QuestionList()
    {
        InitializeComponent();
    }

    public struct QuestionListItem
    {
        public string Question { get; set; }
        public string Answer { get; set; }

        public QuestionListItem(string question, string answer)
        {
            Question = question;
            Answer = answer;
        }
    }

    public void Add(QuestionListItem questionlistItem)
    {
        Panel panel = new Panel();
        panel.Dock = DockStyle.Top;

        Label label = new Label();
        label.MouseHover += Label_MouseHover;
        label.Dock = DockStyle.Fill;
        label.Text = questionlistItem.Question;
        panel.Controls.Add(label);

        Controls.Add(panel);
    }

    //Here (no idea what I just did..)
    private void Label_MouseHover(Object sender, EventArgs e)
    {
        Label label = (Label)sender;
        Panel panel = (Panel)label.Container;
        panel.BackColor = Color.Red;
    }
}

1 个答案:

答案 0 :(得分:1)

我认为你已经添加了你的事件处理程序。问题出在您放入事件处理程序的行中:

document.querySelector('.container').addEventListener('mouseover', function(e) {
  e.preventDefault();
  if (e.target.tagName === 'IMG') {

    //create the div tag for preview
    var myElement = document.createElement('div');
    myElement.className = 'preview';
    e.target.parentNode.appendChild(myElement);
    //Create the image element for preview
    var myImg = document.createElement('img');
    var imgLoc = e.target.src;
    myImg.src = imgLoc;

    myElement.style.left = e.offsetX + 15 + 'px';
    myElement.style.top = e.offsetY + 15 + 'px';
    myImg.style.width = "500px";
    myImg.style.height = "500px";
    myElement.style.zIndex = "-1";
    myElement.appendChild(myImg);

    //When mouse goes out of the image delete the preview
    e.target.addEventListener('mouseout', function handler(d) {
      var myNode = d.target.parentNode.querySelector('div.preview');
      myNode.parentNode.removeChild(myNode);
      e.target.removeEventListener('mouseout', handler, false);
    }, false);

    //place the image 15 inches to the bottom, right of the mouse
    e.target.addEventListener('mousemove', function(f) {
      myElement.style.left = f.offsetX + 15 + 'px';
      myElement.style.top = f.offsetY + 15 + 'px';
    });

  }
}, false);

应该是

Panel panel = (Panel)label.Container;

将Container更改为Parent。

另外,我认为最好使用VS设计器来测试事件处理程序的强类型签名。在您的签名中,您使用EventArgs。我相信它应该是MouseEventArgs。