我制作了动态创建按钮的代码,但是如何为每个按钮分配不同的功能?
for (int i = 0; i < Buttons.Count; i++)
{
Button newBtn = new Button();
newBtn.Content = Buttons[i];
newBtn.Name = "Button" + i.ToString();
newBtn.Height = 23;
stackPanel1.Children.Add(newBtn);
newBtn.Click += new RoutedEventHandler(newBtn_Click);
}
private void newBtn_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello");
}
现在每个按钮显示“Hello”,但我希望它是“Hello1”,“Hello2”....等等。
答案 0 :(得分:6)
如果您可以使用DelegateCommands或RelayCommand属性和DisplayName属性创建对象集合 - 您只需要一个ItemsControl绑定到此Collection,并使用DataTemplate将按钮绑定到Command和Text。
编辑:刚出头
public class MyCommandWrapper
{
public ICommand Command {get;set;}
public string DisplayName {get;set;}
}
在您的viewmodel中
public ObservableCollection<MyCommandWrapper> MyCommands {get;set;}
MyCommands.Add(new MyCommandWrapper(){Command = MyTestCommand1, DisplayName = "Test 1"};
...
你的xaml 中的
<ItemsControl ItemsSource="{Binding MyCommands}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type local:MyCommandWrapper}">
<Button Content="{Binding DisplayName}" Command="{Binding Command}"/>
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
编辑2:如果你需要一个新的动态按钮 - 只需在你的收藏中添加一个新的包装
答案 1 :(得分:2)
for (int i = 0; i < Buttons.Count; i++)
{
Button newBtn = new Button();
newBtn.Content = Buttons[i];
newBtn.Height = 23;
newBtn.Tag=i;
stackPanel1.Children.Add(newBtn);
newBtn.Click += new RoutedEventHandler(newBtn_Click);
}
private void newBtn_Click(object sender, RoutedEventArgs e)
{
Button btn=sender as Button;
int i=(int)btn.Tag;
switch(i)
{
case 0: /*do something*/ break;
case 1: /*do something else*/ break;
default: /*do something by default*/ break;
}
}
答案 2 :(得分:1)
private void newBtn_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var buttonNumber = button.Name.Remove(0, 6);
MessageBox.Show("Hello" + buttonNumber);
}
答案 3 :(得分:1)
检查sender
功能的newBtn_Click
参数。它应该包含被单击的按钮的实例。您可以将其强制转换为按钮并检查名称:
private void newBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
if(btn != null)
{
MessageBox.Show(btn.Name);
}
}
如果您不想检查Name属性,还可以使用Tag属性(http://msdn.microsoft.com/library/system.windows.frameworkelement.tag.aspx)来为其分配任意对象,并在以后检查:
Button newBtn = new Button();
newBtn.Tag = i;
稍后在点击处理程序中:
private void newBtn_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
if(btn != null)
{
if(btn.Tag is int)
MessageBox.Show(String.Format("Hello{0}", btn.Tag));
}
}
我更喜欢使用Tag的解决方案,因为它比从字符串中提取内容更安全。
答案 4 :(得分:1)
newBtn.Click += new RoutedEventHandler((s,e) => MessageBox.Show("hallo"+((Button)s).Name);