我有一个问题。是否可以动态创建按钮并单击事件? 例如,我想创建4个按钮,其中包含4个不同的点击事件。没有必要使用MVVM模式。在开始时我想知道它是否可能,我怎样才能实现这一目标。
答案 0 :(得分:1)
是的,有可能:
public MainWindow()
{
InitializeComponent();
var button = new Button() {Content = "myButton"}; // Creating button
button.Click += Button_Click; //Hooking up to event
myGrid.Children.Add(button); //Adding to grid or other parent
}
private void Button_Click(object sender, RoutedEventArgs e) //Event which will be triggerd on click of ya button
{
throw new NotImplementedException();
}
答案 1 :(得分:1)
叶氏。
public MainWindow()
{
InitializeComponent();
var btn1 = new Button{Content = "btn1"};
//add event handler 1
btn1.Click += ClickHandler1;
//removes event handler 1
btn1.Click -= ClickHandler1;
//add event handler 2
btn1.Click += ClickHandler2;
Panel.Children.Add(btn1);
}
private void ClickHandler1(object sender, RoutedEventArgs e)
{
//do something
}
private void ClickHandler2(object sender, RoutedEventArgs e)
{
//do something
}
private void ClickHandler3(object sender, RoutedEventArgs e)
{
//do something
}
您可以拥有多个事件处理程序,并根据需要添加和删除它们。
答案 2 :(得分:0)
一种可能的方法是将ItemsSource
属性绑定到视图模型中的集合,即
<ItemsControl ItemsSource="{Binding Commands}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Command="{Binding Command}" Content="{Binding DisplayName}" />
<DataTemplate>
<ItemsControl.ItemTemplate>
</ItemsControl>
这当然是使用MVVM。视图模型将具有某种CommandViewModel
的集合,类似于
public class ControlViewModel
{
public Collection<CommandViewModel> Commands { get; }
public ControlViewModel()
{
// Here have logic to determine which commands are added to the collection
var command1 = new RelayCommand(p => ActionForButton1());
var command2 = new RelayCommand(p => ActionForButton2());
Commands = new Collection<CommandViewModel>();
Commands.Add(new CommandViewModel(command1, "Button 1"));
Commands.Add(new CommandViewModel(command2, "Button 2"));
}
private void ActionForButton1()
{
// ....
}
private void ActionForButton2()
{
// ....
}
}
某些课程(CommandViewModel
和RelayCommand
)取自Josh Smith's article。我只是在这里输入代码,你可能想要仔细检查没有语法错误。
我希望它有所帮助