C# - WPF - 以编程方式创建按钮和单击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42030031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 14:00:21  来源:igfitidea点击:

C# - WPF - create buttons and click event programatically

c#wpfeventsbuttonclick

提问by KinectUser

I have a question. Is it possible to create dynamically buttons and click events to it ? For example I want to create 4 buttons with 4 different click events. It is not necessary to make it with MVVM pattern. At the begining I would like just to know is it possible and how can I achieve this.

我有个问题。是否可以动态创建按钮和点击事件?例如,我想用 4 个不同的点击事件创建 4 个按钮。没有必要用 MVVM 模式来制作它。一开始我只想知道这是否可能以及如何实现。

回答by Arman Nagaepetian

Yes it is possible :

对的,这是可能的 :

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

回答by taquion

Yeap.

是的。

 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

    }

You can have several event handlers and add and remove them as needed.

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

回答by Ivan Vargas

One possible way is binding the ItemsSourceproperty to a collection in your view model, i.e.

一种可能的方法是将ItemsSource属性绑定到视图模型中的集合,即

   <ItemsControl ItemsSource="{Binding Commands}">
      <ItemsControl.ItemTemplate>
         <DataTemplate>
             <Button Command="{Binding Command}" Content="{Binding DisplayName}" />
         <DataTemplate>
      <ItemsControl.ItemTemplate>
   </ItemsControl>

This is of course using MVVM. The View Model would have some kind of collection of CommandViewModel, something like

这当然是使用 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()
      {
         // ....
      }
   }

Some of the classes (CommandViewModeland RelayCommand) are taken from Josh Smith's article. I just typed code in here, you might want to double check there are no syntax errors.

一些类(CommandViewModelRelayCommand)取自Josh Smith 的文章。我刚刚在这里输入了代码,您可能需要仔细检查是否有语法错误。

I hope it helps

我希望它有帮助