简体   繁体   中英

How i can Close User Control which were open in pop up from another User Control's button click Event in WPF

I have Main Window into that i have open one user control child1 and have some of textboxes and buttons into that user control.

When the button is clicked at that time I am opening user control name child2 now in user control child2 have on close button and on clicking on that i want to close current user control.

Assuming you are using the Popup class to open your UserControl s you can close the child1 when child2 is closed as following:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM