1

I've got an experience in designing websites with ASP.Net MVC.

I want now to be able to deal with WPF. So, I'm developping a tiny App to learn a few topics like threading, filestreams, and so on.

But, my problem seems really basic :

I've got on my main window a button that fires an action which calls another window. The new windows'aim is to get 2 strings and 2 doubles, to send them back to the main window.

My problem is, that the main window is not launched that way :

MainWindow m = new mainwindow;

And I'd like to do something like :

m.someVariable = somethingFromMySecondWindow.

So, I've tryed to set the main window static, but I got lots of errors, so I removed the "static". I can't access variables from my second window, or any public method.

I don't know if it is needed, but here is the c# code i've already written.

mainWindow :

namespace FlightPlanningDraft1
{
/// <summary>
/// Logique d'interaction pour MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private string _ACModel;
    private string _ACIdentification;
    private double _ACFuelConsumption;
    private double _ACTotalFuel;


    public MainWindow()
    {
        InitializeComponent();
    }

    private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        ChargementAvion c = new ChargementAvion();
        c.Show();
    }

    public void Validation_Avion(string aCModel,string aCIdentification, double aCFuelConsumption, double aCTotalFuel)
    {
        _ACModel = aCModel;
        _ACIdentification = aCIdentification;
        _ACFuelConsumption = aCFuelConsumption;
        _ACTotalFuel = aCTotalFuel;
    }

}
}

My second window

namespace FlightPlanningDraft1
{
/// <summary>
/// Logique d'interaction pour ChargementAvion.xaml
/// </summary>
public partial class ChargementAvion : Window
{

    public ChargementAvion()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //I don't know what to do here.
    }


}
}
4

1 回答 1

2

您可以将事件添加到第二个窗口。MenuItem_Click在( )内订阅它MainWindow,并从第二个窗口 ( ) 触发该事件Button_Click

您可以将任何值传递给您的事件。

public partial class ChargementAvion :Window
{
   public event Action<string> OnDone;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if(OnDone != null)
        { 
           OnDone("any string you want to pass");
        }
    }
}

在主窗口中:

private void MenuItem_Click(object sender, RoutedEventArgs e)
    {
        ChargementAvion c = new ChargementAvion();
        c.OnDone += ResultsHandler;
        c.Show();
    }

  public void ResultsHandler(string result)
  {
     //do what you want ;)
  }

我建议你看看这篇文章。只是为了更熟悉 C# 中的事件和委托。

于 2013-06-09T11:32:18.527 回答