动态地向窗体添加按钮






2.61/5 (17投票s)
如何动态向 Windows 窗体添加按钮。
引言
我正在编写一个小型的 C# 应用程序,需要根据配置文件显示按钮。我在互联网上快速搜索了一下,没有找到太多相关信息,所以我想编写一个简单的示例。
背景
添加按钮的概念与向窗体(WinForms 或 WPF 窗体)添加任何控件完全相同。
Using the Code
下面是一段简单的代码,它创建按钮的实例,更改一些属性,然后将其添加到窗体中。
// Create Instance of a Button
Button myButton = new Button();
// Set some properties
myButton.Visible = true;
// Button Size
myButton.Width = 100;
myButton.Height = 20
// Positon
myButton.Left = 100;
myButton.Top = 100;
myButton.Location = new Point(Left, Top);
// Give to button a name
myButton.Name = Name;
// Text to appear on Button
myButton.Text = "My Button";
// Make the text look nice
Font myFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold);
myButton.Font = myFont;
// This line adds this instance of a button to the form
this.Controls.Add(myButton);
对于 WCF,我们需要做一些稍微不同的事情,因为对象模型不同。
// Create my Button
Button myButton = new Button();
// Create a grid to go on the button
Grid subGrid = new Grid();
// Create a text block and image to go on the grid
TextBlock myTextBlock = new TextBlock();
Image myImage = new Image();
// Get an image from a file
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri("c:\\mylogo.jpg");
bi.EndInit();
// myImage3.Stretch = Stretch.Fill;
myImage.Source = bi;
//put some text on the button
myTextBlock.Text = "My Button";
// add the image and text bock to the grid
subGrid.Children.Add(myImage);
subGrid.Children.Add(myTextBlock);
// set the grid to the content of the button
myButton.Content = subGrid;
// add the button to a grid on the form called grid1.
grid1.Children.Add(myButton);
这在某种程度上是可以的,但是按钮没有任何作用。现在我们需要将点击事件与一些代码关联起来。
//
myButton.Click += new System.EventHandler(this.Button_Click_Code);
// Create a new function
private void Button_Click_Code(object sender, EventArgs e)
{
MessageBox.Show("You clicked my button");
}
如果您创建多个按钮并将它们与同一个 Button_Click_Code
函数关联,则需要有一种方法来确定您按下了哪个按钮。
// Create a new function
private void Button_Click_Code(object sender, EventArgs e)
{
// Try something like this
Button myBut = (Button)sender;
MessageBox.Show(myBut.Name);
switch (myBut.Name)
{
case "button_one" :
// do something
break;
case "button_two" :
// do something else
break;
default:
// everything else
break;
}
}
关注点
动态向窗体添加控件的思想与上述相同,任何类型的任何对象都可以添加到窗体中。
更新
- 2006/12/15:添加了 WPF 按钮的代码。