C#-WPF-创建按钮并用程序点击事件



我有个问题。是否可以动态创建按钮并单击事件?例如,我想创建4个按钮和4个不同的点击事件。没有必要使用MVVM模式。一开始,我只想知道这可能吗?我如何才能做到这一点。

有可能:

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();
}
是的。
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
}

您可以拥有多个事件处理程序,并根据需要添加和删除它们。

一种可能的方法是将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()
{
// ....
}
}

其中一些类(CommandViewModelRelayCommand)取自Josh Smith的文章。我刚在这里输入了代码,你可能想仔细检查一下没有语法错误。

我希望它能帮助

最新更新