表單傳值或父子視窗關閉問題
當我有兩表單(註一)時,我想要在父視窗按一個按鈕後開起子視窗並關閉父視窗,
然後於子視窗按一個按鈕後開啟父視窗並關閉子視窗要如何做?
註一:在VB.NET叫表單(form)、在WPF叫視窗(window)
直接看程式碼吧
一、使用Owner屬性來達成
於父視窗撰寫開啟子視窗並關閉父視窗程式
using System.Windows;
namespace use_owner_property
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenWindow1_Click(object sender, RoutedEventArgs e)
{
Window1 Window1 = new Window1();
Window1.Owner = (Window1)this.Owner;
Window1.Show();
this.Close();
}
}
}
於子視窗撰寫開啟父視窗並關閉子視窗程式
using System.Windows;
namespace use_owner_property
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void btnOpenMainWindow_Click(object sender, RoutedEventArgs e)
{
MainWindow MainWindow = new MainWindow();
MainWindow.Owner = (MainWindow)this.Owner;
MainWindow.Show();
this.Close();
}
}
}
Owner代表可以指定某視窗的所有權可以給其他視窗
二、使用Close方法來達成
於父視窗撰寫開啟子視窗並關閉父視窗程式
using System.Windows;
namespace use_owner_property
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenWindow1_Click(object sender, RoutedEventArgs e)
{
Window1 Window1 = new Window1();
Window1.Show();
this.Close();
}
}
}
於子視窗撰寫開啟父視窗並關閉子視窗程式
using System.Windows;
namespace use_owner_property
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void btnOpenMainWindow_Click(object sender, RoutedEventArgs e)
{
MainWindow MainWindow = new MainWindow();
MainWindow.Show();
this.Close();
}
}
}
參考資料: