WPF 用户控件调用程序没有工作
WPF Usercontrol caller didnt work
我有主窗口。我在主窗口中调用用户控件。我在 mainwindow.loaded 部分调用 Usercontrol1。我想通过单击 Usercontrol1 中的按钮来使用 Usercontrol2 而不是 Usercontrol1。
我的用户控件调用者class:
public class uc_call
{
public static void uc_add(Grid grd, UserControl uc)
{
if (grd.Children.Count > 0)
{
grd.Children.Clear();
grd.Children.Add(uc);
}
else
{
grd.Children.Add(uc);
}
}
}
我的Mainwindow_Loaded(有效):
uc_call.uc_add(Content, new UserControl1());
UserControl1 中的按钮单击函数:
MainWindow mw = new MainWindow();
uc_call.uc_add(mw.Content, new Usercontrol2());
不要创建新的 MainWindow。相反,使用现有的:
var topLevelPanel = Application.Current.MainWindow.Content as Panel;
if (topLevelPanel != null)
{
topLevelPanel.Children.Clear();
topLevelPanel.Children.Add(new Usercontrol2());
}
请注意,即使集合为空,也可以调用 Children.Clear()
。
如果您添加了另一个 Content
属性 来保存要替换子元素的网格:
var mainWindow = (MainWindow)Application.Current.MainWindow;
var grid = mainWindow.Content;
grid.Children.Clear();
grid.Children.Add(new Usercontrol2());
或使用您的静态方法:
var mw = (MainWindow)Application.Current.MainWindow;
uc_call.uc_add(mw.Content, new Usercontrol2());
我有主窗口。我在主窗口中调用用户控件。我在 mainwindow.loaded 部分调用 Usercontrol1。我想通过单击 Usercontrol1 中的按钮来使用 Usercontrol2 而不是 Usercontrol1。
我的用户控件调用者class:
public class uc_call
{
public static void uc_add(Grid grd, UserControl uc)
{
if (grd.Children.Count > 0)
{
grd.Children.Clear();
grd.Children.Add(uc);
}
else
{
grd.Children.Add(uc);
}
}
}
我的Mainwindow_Loaded(有效):
uc_call.uc_add(Content, new UserControl1());
UserControl1 中的按钮单击函数:
MainWindow mw = new MainWindow();
uc_call.uc_add(mw.Content, new Usercontrol2());
不要创建新的 MainWindow。相反,使用现有的:
var topLevelPanel = Application.Current.MainWindow.Content as Panel;
if (topLevelPanel != null)
{
topLevelPanel.Children.Clear();
topLevelPanel.Children.Add(new Usercontrol2());
}
请注意,即使集合为空,也可以调用 Children.Clear()
。
如果您添加了另一个 Content
属性 来保存要替换子元素的网格:
var mainWindow = (MainWindow)Application.Current.MainWindow;
var grid = mainWindow.Content;
grid.Children.Clear();
grid.Children.Add(new Usercontrol2());
或使用您的静态方法:
var mw = (MainWindow)Application.Current.MainWindow;
uc_call.uc_add(mw.Content, new Usercontrol2());