关闭当前的UserControl

Blu*_*Man 4 wpf user-controls children parent

我有一个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
}
Run Code Online (Sandbox Code Playgroud)

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

小智 14

Window.GetWindow(this).Close();
Run Code Online (Sandbox Code Playgroud)

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


Jür*_*ock 1

你试过这个吗?

searchEditPanel.Children.Remove(_EditFileControle);
Run Code Online (Sandbox Code Playgroud)

另一个建议:

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

如果没有:向您的 UserControl 添加一个属性:

public UserControl ParentControl {get;set;}
Run Code Online (Sandbox Code Playgroud)

现在修改您的代码:

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

现在您应该能够执行以下操作:

 // Somewhere in your UserControl
if (this.ParentControl != null)
    this.ParentControl.Children.Remove(this);
Run Code Online (Sandbox Code Playgroud)