Close Current UserControl

I have the main window Window1.xaml; and after some event, I show UserControl EditFile.xaml.

Code behind:

public static int whichSelected = -1;
private void button1_Click(object sender, RoutedEventArgs e)
{
    //searchEditPanel.Children.Clear();
    whichSelected = listViewFiles.SelectedIndex;
    searchEditPanel.Children.Add(_EditFileControle);        //this is Grid
}

And now, how can I close an open / added UserControl from its contents by clicking the Cancel button or something like that?

+4
source share
5 answers

Have you tried this?

searchEditPanel.Children.Remove(_EditFileControle);

Another suggestion:

Maybe this helps: http://sachabarber.net/?p=162

if it is not: add a property to your UserControl:

public UserControl ParentControl {get;set;}

Now change your code:

private void button1_Click(object sender, RoutedEventArgs e)
{
    //searchEditPanel.Children.Clear();
    whichSelected = listViewFiles.SelectedIndex;
    _EditFileControle.ParentControl = this;
    searchEditPanel.Children.Add(_EditFileControle);        //this is Grid
}

Now you can do it:

 // Somewhere in your UserControl
if (this.ParentControl != null)
    this.ParentControl.Children.Remove(this);
+1
source
Window.GetWindow(this).Close();

You do not need to use a new variable, you can use it directly.

+11

, "", .

Thus, it will no longer be displayed, but will still be present in the visual tree if you need to reuse it later.

+2
source

In the button click handler, try:

Window parentWindow = (Window)this.Parent;
parentWindow.Close();
+2
source
private void Button_Click(object sender, RoutedEventArgs e)
{

    (this.Parent as searchEditPanel).Children.Remove(this);

}
0
source

Source: https://habr.com/ru/post/1747963/


All Articles