我一直在研究将控件添加到C#中另一个父控件的方法, 我知道有很多方法可以做到这一点,而要做的简单事情就是遵循这些方法-但是,我很好奇无法使用以下方法做到这一点:
方法A
Container.Controls.Add(new Button //Add the control straight to the parent
{
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
}.Click += DesignerButton_OnClick); //This is the only method Intellisense recognised, even though it does not work...
与有效的方法相比:
方法B
Button NewButton = new Button();
NewButton.Name = "Button Name";
NewButton.Text = "Button Text";
NewButton.Size = new Size(69, 69);
NewButton.Location = new Point(420, 420);
NewButton.Click += DesignerButton_OnClick; //Add the handler
Container.Controls.Add(NewButton); //Add control to parent
我高度怀疑这是我正在调用的函数的问题,但是为了解决问题,这里的问题很简单-
处理功能
private static void DesignerButton_OnClick(object Sender, EventArgs Ev)
{
//Do stuff
}
问题
是否可以将事件处理程序添加到通过方法A 生成的按钮上?
答案 0 :(得分:2)
这是一种方便的扩展方法:
public static class Ex
{
public static T Attach<T>(this T sender, Action<T> addHandler)
{
addHandler(sender);
return sender;
}
}
然后您可以这样编写代码:
void Main()
{
var btn = new Button()
{
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
}.Attach(b => b.Click += DesignerButton_OnClick);
btn.PerformClick();
}
private static void DesignerButton_OnClick(object Sender, EventArgs Ev)
{
Console.WriteLine("Clicked!");
}
当我运行它时,它将Clicked!
写到控制台。
您可以将Attach
调用链接起来,以连接多个事件。
现在,您可以轻松地将其包装在Container.Controls.Add(...)
调用中。
答案 1 :(得分:1)
您可以这样做:
new Button
{
Parent = Container, // the same as Container.Controls.Add
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
}.Click += DesignerButton_OnClick;
或者如果您需要局部变量:
var NewButton = new Button
{
Parent = Container,
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
};
NewButton.Click += DesignerButton_OnClick;
答案 2 :(得分:0)
您可以创建扩展方法以返回添加的控件:
// Case A
public static Control AddAndReturn(this ControlCollection controls, Control control)
{
controls.Add(control);
return control;
}
// Case B
public static Control Add(this ControlCollection controls, Control control, bool returnControl)
{
controls.Add(control);
if (returnControl)
return control;
return null;
}
您可以根据需要使用它:
// Case A
Container.Controls.AddAndReturn(new Button
{
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
}).Click += DesignerButton_OnClick;
// Case B
Container.Controls.Add(new Button
{
Name = "Button Name",
Text = "Button Text",
Size = new Size(69, 69),
Location = new Point(420, 420)
}, returnControl: true).Click += DesignerButton_OnClick;