【问题标题】:WPF Usercontrol caller didnt workWPF用户控件调用者没有工作
【发布时间】:2017-12-07 10:12:09
【问题描述】:

我有主窗口。我在主窗口中调用用户控件。我在 mainwindow.loaded 部分调用 Usercontrol1。我想通过单击 Usercontrol1 中的按钮来使用 Usercontrol2 而不是 Usercontrol1。

我的用户控件调用者类:

 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());

【问题讨论】:

    标签: c# wpf wpf-controls


    【解决方案1】:

    不要创建新的 MainWindow。而是使用现有的:

    var topLevelPanel = Application.Current.MainWindow.Content as Panel;
    
    if (topLevelPanel != null)
    {
        topLevelPanel.Children.Clear();
        topLevelPanel.Children.Add(new Usercontrol2());
    }
    

    请注意,即使集合为空,调用 Children.Clear() 也无妨。


    如果您添加了另一个 Content 属性,该属性包含要替换子元素的 Grid:

    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());
    

    【讨论】:

    • 我希望用户控件在主窗口内的网格上进行更改。当我按照你说的做时,主窗口中的所有对象都丢失了。如何让主窗口的对象保持不变?
    • 我的设计和 usercontrol1:ibb.co/fkOcVG -- 我希望 usercontrol2 替换 usercontrol1 但是当点击按钮时:ibb.co/npb9cw
    • topLevelPanel 这是您分配给主窗口的内容(即mw.Content)属性的顶级网格。或者您是否添加了另一个 Content 字段或属性?
    猜你喜欢
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 2010-10-01
    • 1970-01-01
    相关资源
    最近更新 更多