将参数添加到WPF中的Button_Click事件

时间:2015-07-28 15:29:52

标签: c# wpf xaml

我知道它之前已被问过,但经过大约一个小时的搜索后,我无法找出将参数添加到事件处理程序的最简单和最简单的方法。默认情况下,这些处理程序的模板只能接受(object sender,RoutedEventArgs e)参数。我发现很难相信没有一个干净简单的方法来做到这一点,因为我想这个问题经常发生。但是我是WPF的新手,所以如果有人可以就此问题提供一些指导我的代码如下。

点击此按钮时

<Button Height="23" VerticalAlignment="Bottom" Margin="150, 0, 0, 2" Content="Terminate All Processes" Width="135" HorizontalAlignment="Left" Click="TerminateAll_Click" Name="TerminateAll"/>

我需要一个关闭所有进程的事件。要做到这一点,我需要将所有进程的列表传递给事件处理程序,我还没有发现一种简单的方法。感谢您提供的任何帮助。

编辑:这是我的.cs文件         public partial class MainWindow:Window     {         public MainWindow()         {             的InitializeComponent();             ObservableCollection procs = new ObservableCollection();

        Processes.getProcs(ref procs);
        lview.ItemsSource = procs;
    }

    private void TerminateAllProcesses(ObservableCollection<Proc> procs)
    {
        foreach (Proc p in procs)
        {
            if (!p.Pro.HasExited) { p.Pro.Kill(); }
        }
    }

    public void TerminateAll_Click(object sender, RoutedEventArgs e)
    {

    }
}

1 个答案:

答案 0 :(得分:4)

I need to pass the list of all the processes to the event handler

Why? The button fires the event, so it has to have a known parameter list. Plus, it has no knowledge of the list of processes, so it wouldn't know what to pass in anyway. However, there's nothing from stopping you from firing off another method from the click event:

private void TerminateAll_Click(object sender, RoutedEventArgs e) 
{
    List<string> processes = // get the list
    TerminateAll(processes);
}

public void TerminateAll(List<string> processes)
{
   foreach(string process in processes)
     Terminate(process);
}
private void Terminate(string process)
{
  // terminate the process
}