Close current UserControl

五迷三道 提交于 2019-12-21 05:16:10

问题


I have a Window1.xaml main Window; and after some event, I display a UserControl EditFile.xaml.

The code behind is:

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 the opened/added UserControl from its content by clicking a Cancel button or something like that?


回答1:


Have you tried this?

searchEditPanel.Children.Remove(_EditFileControle);

Another Suggestion:

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

if it doesn't: Add a property to your UserControl:

public UserControl ParentControl {get;set;}

Now modify 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 should be able to do this:

 // Somewhere in your UserControl
if (this.ParentControl != null)
    this.ParentControl.Children.Remove(this);



回答2:


Window.GetWindow(this).Close();

You don't need to use a new variable, you can use it directly.




回答3:


You could set the Visibility property of the control you want to "close" to Collapsed.

This way it will not be displayed anymore but will still be present in the visual tree if you need to reuse it later.




回答4:


In your button click handler try :

Window parentWindow = (Window)this.Parent;
parentWindow.Close();



回答5:


private void Button_Click(object sender, RoutedEventArgs e)
{

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

}


来源:https://stackoverflow.com/questions/2949089/close-current-usercontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!