关闭当前的UserControl

时间:2010-06-01 10:52:58

标签: wpf user-controls parent children

我有一个Window1.xaml主窗口;在一些事件之后,我显示一个UserControl EditFile.xaml。

背后的代码是:

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
}

现在,如何通过单击“取消”按钮或类似内容来关闭已打开/添加的UserControl?

5 个答案:

答案 0 :(得分:12)

Window.GetWindow(this).Close();

您不需要使用新变量,您可以直接使用它。

答案 1 :(得分:2)

您可以将要“关闭”的控件的可见性属性设置为折叠

这种方式不再显示,但如果您以后需要重复使用,它仍然会出现在可视化树中。

答案 2 :(得分:2)

在按钮点击处理程序中尝试:

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

答案 3 :(得分:1)

你试过这个吗?

searchEditPanel.Children.Remove(_EditFileControle);

另一个建议:

也许这会有所帮助:http://sachabarber.net/?p=162

如果不是:将属性添加到UserControl:

public UserControl ParentControl {get;set;}

现在修改你的代码:

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

现在你应该能够做到这一点:

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

答案 4 :(得分:0)

private void Button_Click(object sender, RoutedEventArgs e)
{

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

}