简体   繁体   English

向 WPF 中的 Button_Click 事件添加参数

[英]Adding a Parameter to a Button_Click event in WPF

I know it has been asked before but after about an hour of searching I am unable to figure out the simplest and easiest way to add a parameter to an event handler.我知道之前有人问过它,但经过大约一个小时的搜索,我无法找出将参数添加到事件处理程序的最简单和最简单的方法。 By default, the template for these handlers can only accept (object sender, RoutedEventArgs e) arguments.默认情况下,这些处理程序的模板只能接受 (object sender, RoutedEventArgs e) 参数。 I find it hard to believe that there isn't a clean and easy way to do this because I imagine this problem occurs quite frequently.我发现很难相信没有一种干净且简单的方法可以做到这一点,因为我认为这个问题经常发生。 However I am new to WPF so if someone could provide some guidance on this issue my code is below.但是我是 WPF 的新手,所以如果有人可以就这个问题提供一些指导,我的代码如下。

When clicking on this button单击此按钮时

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

I need an event to fire off that closes all my processes.我需要一个事件来关闭我的所有进程。 To do this though, i need to pass the list of all the processes to the event handler and I have yet to discover an easy way of doing this.不过要做到这一点,我需要将所有进程的列表传递给事件处理程序,但我还没有找到一种简单的方法来做到这一点。 Thank you for any help you can provide.感谢您提供任何帮助。

Edit: This is my .cs file编辑:这是我的 .cs 文件

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ObservableCollection<Proc> procs = new ObservableCollection<Proc>();

        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)
    {

    }
}

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:但是,没有什么可以阻止您从 click 事件触发另一个方法:

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM