向 WPF 中的 Button_Click 事件添加参数 [英] Adding a Parameter to a Button_Click event in WPF

查看:63
本文介绍了向 WPF 中的 Button_Click 事件添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前有人问过它,但经过大约一个小时的搜索后,我无法找出将参数添加到事件处理程序的最简单和最简单的方法.默认情况下,这些处理程序的模板只能接受 (object sender, RoutedEventArgs e) 参数.我发现很难相信没有一种干净且简单的方法可以做到这一点,因为我认为这个问题经常发生.但是我是 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. 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.

点击这个按钮时

<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.

这是我的 .cs 文件

This is my .cs file

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

为什么?button 触发事件,因此它必须有一个已知的参数列表.另外,它不知道进程列表,所以无论如何它都不知道要传递什么.但是,没有什么可以阻止您从点击事件中触发另一个方法:

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
}

这篇关于向 WPF 中的 Button_Click 事件添加参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆