Adding a Parameter to a Button_Click event in WPF

依然范特西╮ 提交于 2020-02-25 08:32:44

问题


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.

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

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

    }
}

回答1:


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
}


来源:https://stackoverflow.com/questions/31680854/adding-a-parameter-to-a-button-click-event-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!