查找打开新窗口的方法名称(c#wpf)

时间:2014-06-11 13:03:12

标签: c# wpf events event-handling window

我正在尝试找到一种获取方法调用的字符串名称的方法,该方法调用会弹出一个新窗口。我有三个按钮单击事件处理程序,它将打开新窗口,但我需要知道哪个叫.Show();

    private void buttonSettingsPortfolio1_Click(object sender, RoutedEventArgs e)
    {
        var settingsWindow = new MobilityPortfolioSettings();
        settingsWindow.Show();
    }

    private void buttonSettingsPortfolio2_Click(object sender, RoutedEventArgs e)
    {
        var settingsWindow = new MobilityPortfolioSettings();
        settingsWindow.Show();
    }

    private void buttonSettingsPortfolio3_Click(object sender, RoutedEventArgs e)
    {
        var settingsWindow = new MobilityPortfolioSettings();
        settingsWindow.Show();
    }

我不想拥有三个独立的窗户!是否有一个打开事件处理程序参数,我可以从?

获取调用者

3 个答案:

答案 0 :(得分:0)

下面 Console.write(triggeredBy);您可以通过记录到文件或其他方式输出值。该值将指示代码所采用的路径。

private void buttonSettingsPortfolio1_Click(object sender, RoutedEventArgs e)
    {
        Open("buttonSettingsPortfolio1_Click");
    }

    private void buttonSettingsPortfolio2_Click(object sender, RoutedEventArgs e)
    {
        Open("buttonSettingsPortfolio2_Click");
    }

    private void buttonSettingsPortfolio3_Click(object sender, RoutedEventArgs e)
    {
       Open("buttonSettingsPortfolio3_Click");
    }

    private Open(string triggeredBy){
        Console.write(triggeredBy); // You can write to file or output in some different way here.
        var settingsWindow = new MobilityPortfolioSettings();
        settingsWindow.Show();
}

答案 1 :(得分:0)

好吧,您只需在MobilityPortfolioSettings类中添加一个公共变量,并在每个方法中设置其值,例如:在buttonSettingsPortfolio1_Click中添加MobilityPortfolioSettings.Variable = 1,等等。

答案 2 :(得分:0)

试试这个:

  1. 将发件人转换为按钮,然后获取其名称。
  2. 更改MobilityPortfolioSettings构造函数,使其需要字符串参数。
  3. 将按钮名称传递给构造函数。

    private void buttonSettingsPortfolio1_Click(object sender, RoutedEventArgs e)
    {
        string buttonName = "";
        if (sender is Button)
            buttonName = ((Button)sender).Name;
    
        Window settingsWindow = new MobilityPortfolioSettings(buttonName);
        settingsWindow.Show();
    }
    
  4. BTW使用Window作为变量类型而不是var。

    干杯