在 C# 中创建用户控件时遇到问题
Trouble creating user control in C#
我正在用 C# 创建用户控件,但我不知道如何处理事件。我想在鼠标悬停时更改面板的背景色 属性,但它不起作用。
代码:
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 设计器来测试事件处理程序的强类型签名是什么。在您的签名中,您使用 EventArgs。我认为应该改为 MouseEventArgs。
我正在用 C# 创建用户控件,但我不知道如何处理事件。我想在鼠标悬停时更改面板的背景色 属性,但它不起作用。
代码:
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 设计器来测试事件处理程序的强类型签名是什么。在您的签名中,您使用 EventArgs。我认为应该改为 MouseEventArgs。