2014-10-09 98 views
1

我有3个窗口,我可以在它们之间切换。我遇到的问题是窗口不隐藏时不保存数据。我想他们正在被处置,但我不知道如何。我在两个窗口上有一个文本框来测试这个。当只有两个窗口时它工作正常,但添加第三个窗口就产生了这个问题。这是我的主窗口。WPF,在多个窗口之间切换而不处置

public partial class MainWindow : Window 
{ 
    private AutoImport auto; 
    private DTLegacy dleg; 

    public MainWindow() 
    { 
     InitializeComponent(); 
    } 

    public MainWindow(AutoImport parent) 
    { 
     InitializeComponent(); 
     auto = parent; 
    } 

    public MainWindow(DTLegacy parent) 
    { 
     InitializeComponent(); 
     dleg = parent; 
    } 

    private void btnAutoImport_Click(object sender, RoutedEventArgs e) 
    { 
     this.Hide(); 
     if (auto == null) { auto = new AutoImport(); } 
     auto.Show(); 
    } 

    private void btnDTLegacy_Click(object sender, RoutedEventArgs e) 
    { 
     this.Hide(); 
     if (dleg == null) { dleg = new DTLegacy(); } 
     dleg.Show(); 
    } 
} 

窗口1

public AutoImport() 
{ 
    InitializeComponent(); 
} 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    this.Hide(); 
    MainWindow main = new MainWindow(this); 
    main.Show(); 
} 

窗口2

public DTLegacy() 
{ 
    InitializeComponent(); 
} 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    this.Hide(); 
    MainWindow main = new MainWindow(this); 
    main.Show(); 
} 

我想答案可能是创建一个窗口类的某种,但我不知道这是什么会看起来像。

+0

有两个概念。在'wpf'(和'mvvm'一起)中,最好是在处理窗口的时候。只需保留所有需要恢复状态的视图模型:焦点,选择,输入/选择值等。另一个概念是创建窗口一次,然后永远不要处理它们(着名的'winforms''隐藏技巧),它应该仍然在wpf中工作。在启动时创建Windows实例,永远不会再创建实例(就像你做的那样!),但是调用该实例的'Hide()'/'Show()'方法。 – Sinatr 2014-10-09 14:44:34

回答

1

为什么每次都创建一个新的MainWindow实例?你目前正在隐藏它,所以再次展示它而不是创建一个新的。 假设这是你的应用程序的主窗口和AutoImport/DTLegacy是“孩子”窗口,一个解决办法是到MainWindow实例传递的“孩子”窗口的参数,这样就可以方便地调用.Show()

private MainWindow parent; 
public AutoImport(MainWindow parent) 
{ 
    InitializeComponent(); 
    this.parent = parent; 
} 

private void Button_Click(object sender, RoutedEventArgs e) 
{ 
    this.Hide(); 
    this.parent.Show(); 
}