我有一个按钮数组,它在运行时动态生成。我的代码中有按钮单击功能,但我找不到在代码中设置按钮的单击名称的方法。所以,
XAML的等效代码是什么:
<Button x:Name="btn1" Click="btn1_Click">
或者,我应该为“????”放置什么在以下代码中:
Button btn = new Button()
{
{1}} {
{1}}
答案 0 :(得分:38)
Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;
private void btn1_Click(object sender, RoutedEventArgs e)
{
// do something
}
答案 1 :(得分:11)
以下应该可以解决问题:
btn.Click += btn1_Click;
答案 2 :(得分:3)
// sample C#
public void populateButtons()
{
int xPos;
int yPos;
Random ranNum = new Random();
for (int i = 0; i < 50; i++)
{
Button foo = new Button();
Style buttonStyle = Window.Resources["CurvedButton"] as Style;
int sizeValue = ranNum.Next(50);
foo.Width = sizeValue;
foo.Height = sizeValue;
foo.Name = "button" + i;
xPos = ranNum.Next(300);
yPos = ranNum.Next(200);
foo.HorizontalAlignment = HorizontalAlignment.Left;
foo.VerticalAlignment = VerticalAlignment.Top;
foo.Margin = new Thickness(xPos, yPos, 0, 0);
foo.Style = buttonStyle;
foo.Click += new RoutedEventHandler(buttonClick);
LayoutRoot.Children.Add(foo);
}
}
private void buttonClick(object sender, EventArgs e)
{
//do something or...
Button clicked = (Button) sender;
MessageBox.Show("Button's name is: " + clicked.Name);
}
答案 3 :(得分:1)
我认为WPF不支持您要实现的目标,即使用方法名称或btn1.Click =“btn1_Click”为按钮分配方法。您将不得不使用上述答案中建议的方法,即使用适当的方法注册按钮点击事件 btn1。点击+ = btn1_Click;
答案 4 :(得分:0)
你应该放在
之下btn.Click = btn.Click + btn1_Click;