Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中创建用户控件时遇到问题#_C#_.net_Winforms_User Controls_Panel - Fatal编程技术网

C# 在C中创建用户控件时遇到问题#

C# 在C中创建用户控件时遇到问题#,c#,.net,winforms,user-controls,panel,C#,.net,Winforms,User Controls,Panel,我正在用C#创建一个用户控件,但我不知道如何处理事件。我想更改鼠标悬停时面板的backcolor属性,但它不起作用 代码: public partial class QuestionList : UserControl { public QuestionList() { InitializeComponent(); } public struct QuestionListItem { public string Quest

我正在用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;
    }
}

我认为您已经正确添加了事件处理程序。问题在于您在事件处理程序中放置的行:

Panel panel = (Panel)label.Container;
应该是

Panel panel = (Panel)label.Parent;
将容器更改为父容器


此外,我认为最好使用VS designer来测试事件处理程序的强类型签名是什么。在签名中,使用EventArgs。我认为应该用MouseEventArgs来代替。

哦,我的天啊,谢谢你,它很管用!!祝你过得愉快:是你。直到现在,我才检查我的旧线程,我投票赞成好的逻辑答案。谢谢你提供的即时和有用的帮助,你是个好人:)@Tayab没问题。^ u^谢谢那将拯救我的一天。