从按钮加载新的WPF窗口

时间:2013-10-07 18:58:32

标签: c# wpf

我创建了另一个WPF窗口..说window2.xaml。我有一个按钮..然后点击我希望它加载该窗口..我已经尝试谷歌搜索但似乎没有任何工作。它只是加载一个空白页面。我知道这很简单,但我真的找不到如何通过我的搜索来做到这一点。

这就是我的尝试:

GameClock temp = new GameClock();
temp.ShowDialog();  //just shows blank window
temp.Show();  //just shows a blank window too
编辑:我发现了问题所在。我拿出了初始化组件,因为出现了错误。我认为这只是需要主窗口的东西。当我把它放回去时,它有效。谢谢,大家。

2 个答案:

答案 0 :(得分:1)

在创建GameClock实例之前,您可能需要阅读XAML文件。像这样:

GameClock clock;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
clock = (GameClock)XamlReader.Load(fs);

JAB

答案 1 :(得分:1)

试试这个......你可以像通用的方法一样使用

private void button_ItemClick(object sender, ItemClickEventArgs e)
{
    try
    {
        OpenWin("window2", new Uri(@"window2.xaml", UriKind.Relative), "Window2Label");
    }
    catch (Exception ex)
    {
        Message.Show(ex);
    }
}

public static DocumentPanel OpenWin(string namePainelItem, Uri xamlPath, string caption = "", RoutedEventHandler unloadEvent = null, bool closeOpenWin = false)
{
    try
    {        
        if (closeOpenWin)
        {
            CloseWin(namePainelItem, false);
        }

        DocumentPanel panel1 = GetWin(namePainelItem);
        if (panel1 == null)
        {
            panel1 = new DocumentPanel();
            panel1.Caption = caption;
            panel1.Name = namePainelItem;
            panel1.Content = xamlPath;

            if (unloadEvent != null)
            {
                panel1.Unloaded += unloadEvent;                        
            }            

            hdl.dockLayoutManager.DockController.Insert(hdl.documentGroup1, panel1, 1);
            hdl.dockLayoutManager.DockController.ActiveItem = panel1;
        }
        else
        {
            if (panel1.Visibility != Visibility.Visible)
                panel1.Visibility = Visibility.Visible;

            if(panel1.IsClosed)
                panel1.Closed = false;                    

            hdl.dockLayoutManager.DockController.ActiveItem = panel1;
        }
        return panel1;
    }
    catch (Exception ex)
    {
        Message.Show(ex);                
    }
    return new DocumentPanel();
}


public static void CloseWin(string namePainelItem)
{
    try
    {
        BaseLayoutItem item = hdl.dockLayoutManager.GetItem(namePainelItem);

        if (item != null)
        {
            hdl.documentGroup1.Items.Remove(item);
            hdl.dockLayoutManager.DockController.RemovePanel((DocumentPanel)item);
            item = null;
        }
    }
    catch (Exception ex)
    {
        Message.Show(ex);
    }
}