2010-06-01 117 views
3

我有一个Window1.xaml主窗口;并在某些事件发生后,我显示一个UserControl EditFile.xaml。关闭当前UserControl

后面的代码是:

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 
} 

而现在,我怎么能收从其内容中打开/添加的用户控件通过点击取消按钮或类似的东西?

回答

1

你试过这个吗?

searchEditPanel.Children.Remove(_EditFileControle); 

另一个建议:

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

,如果它不:一个属性添加到您的用户控件:

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); 
+1

是的 - 工作,但从父母(窗口1)运行。我必须从我的孩子(EditFile.xaml.cs文件)关闭UserControl通过点击它一些取消按钮。 – BlueMan 2010-06-01 11:46:49

1

您可以设置可见性要控制的属性“关闭”到折叠

这种方式将不会再显示,但如果您稍后需要重用它,它仍会存在于可视化树中。

2

在您的按钮单击处理程序尝试:

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

未将对象引用设置为对象的实例。 – albatross 2016-01-12 11:52:54

10
Window.GetWindow(this).Close(); 

你并不需要使用一个新的变量,你可以用它直。

+0

只是想知道...这会导致'UserControl.Unloaded'事件引发? – IAbstract 2015-09-10 13:15:15