如何关闭用户控件,它是从另一个用户控件的按钮弹出打开,单击WPF中的事件

时间:2016-09-15 12:59:40

标签: c# .net wpf

我有主窗口,我打开了一个用户控件child1,并在该用户控件中有一些文本框和按钮。

当我点击该按钮时,我正在用户控件中打开用户控件名称child2,child2有关闭按钮,点击后我要关闭当前用户控件。

1 个答案:

答案 0 :(得分:2)

假设您使用Popup课程打开UserControl 关闭child1时,您可以关闭child2,如下所示:

MainWindow.xaml.cs

//Opens the child1 UserControl from MainWindow
private void button_Click(object sender, RoutedEventArgs e)
{
    UserControl1 child1 = new UserControl1();
    Popup p = new Popup();
    child1.ParentPopup = p;
    p.Child = child1;
    p.IsOpen = true;
}


UserControl1.xaml.cs

public Popup ParentPopup { get; set; }
public UserControl1()
{
    InitializeComponent();
}

//Opens the child2 UserControl from child1 UserControl
private void button_Click(object sender, RoutedEventArgs e)
{
    UserControl2 child2 = new UserControl2();
    Popup p = new Popup();
    child2.Unloaded += Child2_Unloaded;
    child2.ParentPopup = p;
    p.Child = child2;
    p.IsOpen = true;
}

//Closes the child1 UserControl when child2 is closed
private void Child2_Unloaded(object sender, RoutedEventArgs e)
{
   ParentPopup.IsOpen = false;
}


UserControl2.xaml.cs

public Popup ParentPopup { get; set; }

public UserControl2()
{
    InitializeComponent();
}

//Closes the child2 UserControl
private void button_Click(object sender, RoutedEventArgs e)
{
    ParentPopup.IsOpen = false;
}
相关问题