从启动窗口获取值

时间:2015-08-25 19:43:47

标签: c# wpf

我使用以下代码更改了app.xaml的启动窗口:

Startup="ApplicationStart"

app.xaml.cs文件是这个方法:

    private void ApplicationStart(object sender, StartupEventArgs e)
    {
        Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

        ChooseAccountWindow chooseAccountWindow = new ChooseAccountWindow();
        chooseAccountWindow.ShowDialog();
    }

窗口代码(ChooseAccountWindow()):

public partial class ChooseAccountWindow : MetroWindow
{
    public ChooseAccountWindow()
    {
        InitializeComponent();
    }

    private void btnDastaschentuch2013_Click(object sender, RoutedEventArgs e)
    {
        //send value "dastaschentuch2013" to the main window
    }

    private void btnSkeptar_de_Click(object sender, RoutedEventArgs e)
    {
        //send value "skeptar_de" to the main window
    }

    private void btnAsdf_de_Click(object sender, RoutedEventArgs e)
    {
        //send value "asdf_de" to the main window
    }
}

如果按下其中一个按钮,则应将值发送到主代码。我怎样才能做到这一点?

答案

我必须更改MainWindow.xaml.cs代码:

namespace EbayManager
{
public partial class MainWindow : MetroWindow
{
    private string selectedAccount;

    public MainWindow()
    {
        InitializeComponent();
    }

    public MainWindow(string selectedAccount): this()
    {
        this.selectedAccount = selectedAccount;


    }
}
}

2 个答案:

答案 0 :(得分:2)

public partial class ChooseAccountWindow : MetroWindow
{
    public string Result { get; set; }

    public ChooseAccountWindow()
    {
        InitializeComponent();
    }

    private void btnDastaschentuch2013_Click(object sender, RoutedEventArgs e)
    {
        this.Result = "dastaschentuch2013";
        this.Close();
    }

    private void btnSkeptar_de_Click(object sender, RoutedEventArgs e)
    {
        this.Result = "skeptar_de";
        this.Close();
    }

    private void btnTrachsel_de_Click(object sender, RoutedEventArgs e)
    {
        this.Result = "trachsel_de";
        this.Close();
    }
}

在App.xaml中删除StartupUri以防止自动打开主窗口

在App.xaml.cs中:

private void ApplicationStart(object sender, StartupEventArgs e)
{
    Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

    ChooseAccountWindow chooseAccountWindow = new ChooseAccountWindow();
    chooseAccountWindow.ShowDialog();

    MainWindow main = new MainWindow(chooseAccountWindow.Result);
    // insert your startup uri class name instead of MainWindow;
    // add constructor to this window that will take string as input parameter
    main.Show();
}

答案 1 :(得分:1)

如果我读了你,你可以像这样引用主窗口:

Application.Current.MainWindow and then set a property on it.


void Button_Click(object sender, RoutedEventArgs e)
{
    Application.Current.MainWindow.MyProperty = "SomeValue";
    MainWindow.ShowDialog();
    this.Close();
}