wpf 关闭当前用户控件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2949089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Close current UserControl
提问by BlueMan
I have a Window1.xaml main Window; and after some event, I display a UserControl EditFile.xaml.
我有一个 Window1.xaml 主窗口;在一些事件之后,我显示一个 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?
现在,如何通过单击“取消”按钮或类似的东西从其内容中关闭打开/添加的 UserControl?
采纳答案by Jürgen Steinblock
Have you tried this?
你试过这个吗?
searchEditPanel.Children.Remove(_EditFileControle);
Another Suggestion:
另一个建议:
Maybe this helps: http://sachabarber.net/?p=162
也许这有帮助:http: //sachabarber.net/?p= 162
if it doesn't: Add a property to your UserControl:
如果没有:向您的 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);
回答by Dino MARIANO
Window.GetWindow(this).Close();
You don't need to use a new variable, you can use it directly.
不需要使用新变量,直接使用即可。
回答by Pragmateek
You could set the Visibilityproperty of the control you want to "close" to Collapsed.
您可以将要“关闭”的控件的Visibility属性设置为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.
这样它就不会再显示了,但如果您以后需要重用它,它仍然会出现在可视化树中。
回答by inside
In your button click handler try :
在您的按钮单击处理程序中尝试:
Window parentWindow = (Window)this.Parent;
parentWindow.Close();
回答by AliAzra
private void Button_Click(object sender, RoutedEventArgs e)
{
(this.Parent as searchEditPanel).Children.Remove(this);
}