从WPF中的另一个用户控件打开用户控件

从WPF中的另一个用户控件打开用户控件

问题描述:





i有一个主窗口,我使用用户控件,例如在窗口内打开的表格,



i在用户控件中有关闭按钮,如何删除或清除打开的用户控件并打开另一个用户控件?



我尝试过:



private void btnCancel_Click(object sender,RoutedEventArgs e)

{



((Panel)this.Parent).Children.Remove(this); //删除已打开的用户控件



winMain w = new winMain();

OpenUserControls.OpenUCMain(w.MainContent,new ucMain() ); //不要打开另一个用户控件

}



//我的开放式用户控制方法(ucMain)



public static void OpenUCMain(Grid grd,UserControl uc)

{

if(grd.Children.Count == 0)

{

grd.Children.Add(uc);

}

}

Hi

i have a main window and i use user control such as a form that open inside window,

i have close button inside user control, how can i remove or clear opened user control and open another user control?

What I have tried:

private void btnCancel_Click(object sender, RoutedEventArgs e)
{

((Panel)this.Parent).Children.Remove(this); // remove opened user control

winMain w = new winMain();
OpenUserControls.OpenUCMain(w.MainContent, new ucMain()); // dont open another user control
}

// my method for open user control (ucMain)

public static void OpenUCMain(Grid grd, UserControl uc)
{
if (grd.Children.Count == 0)
{
grd.Children.Add(uc);
}
}

如果要删除的控件不是UserControl上要删除它的子控件,则不应该这样做。



您应该做的是在UserControl中公开请求删除其他控件的事件。此事件由父表单订阅。然后父表格决定是否适当且安全地删除其他控件然后执行它。



控件的所有者(父母)应该处理孩子控制,而不是另一个儿童控制。
If the control you want to remove is not a child on the UserControl that wants it removed, it should NOT be doing it.

What you should be doing is exposing an event in your UserControl that requests the other control to be removed. This event is subscribed to by the parent form. The parent form would then decide if it's appropriate and safe to remove the other control and then do it.

The owner (parent) of a control should be handling the child control, not left up to another child control.