如何在不在WPF中打开新窗口的情况下加载新的用户控件?

时间:2009-05-04 08:08:02

标签: c# wpf user-controls

我把this WPF application http://tanguay.info/web/index.php?pg=codeExamples&id=164放在一起

http://tanguay.info/web/index.php?pg=codeExamples&id=164

读取客户的XML文件,允许用户编辑并保存回来,并且一切正常

但是,当用户点击“管理客户”页面上的保存时,我希望应用程序“返回”“显示客户”页面。

“页面”是在shell中动态加载的用户控件,如下所示:

using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Reflection;
using TestDynamicForm123.View;

namespace TestDynamicForm123
{
    public partial class Shell : Window
    {
        private Dictionary<string, IBaseView> _userControls = new Dictionary<string, IBaseView>();

        public Dictionary<string, IBaseView> GetUserControls()
        {
            return _userControls;
        }

        public Shell()
        {
            InitializeComponent();

            List<string> userControlKeys = new List<string>();
            userControlKeys.Add("WelcomeView");
            userControlKeys.Add("CustomersView");
            userControlKeys.Add("ManageCustomersView");
            Type type = this.GetType();
            Assembly assembly = type.Assembly;
            foreach (string userControlKey in userControlKeys)
            {
                string userControlFullName = String.Format("{0}.View.{1}", type.Namespace, userControlKey);
                IBaseView userControl = (IBaseView)assembly.CreateInstance(userControlFullName);
                _userControls.Add(userControlKey, userControl);
            }

            //set the default page
            btnWelcome.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
        }

        private void btnGeneral_Click(object sender, RoutedEventArgs e)
        {
            PanelMainContent.Children.Clear();
            Button button = (Button)e.OriginalSource;
            PanelMainWrapper.Header = button.Content;
            Type type = this.GetType();
            Assembly assembly = type.Assembly;

            IBaseView userControl = _userControls[button.Tag.ToString()] as IBaseView;
            userControl.SetDataContext();


            PanelMainContent.Children.Add(userControl as UserControl);
        }
    }
}

因此,当加载 ManageCustomersView 并处理点击时,我会尝试返回 CustomersView 页面,该页面有效,但会打开一个新窗口< strong>所以每次用户编辑客户时,都会弹出一个新窗口。

private void OnSave(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
    Customer customer = e.Parameter as Customer;
    Customer.Save(customer);

    //go back to default back
    Shell shell = new Shell();
    Button btnCustomers = shell.FindName("btnCustomers") as Button;
    btnCustomers.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
    shell.Show();
}

如何在一个UserControl中更改上面的代码,使其 parent 卸载当前用户控件并加载另一个,而不是像现在一样弹出另一个应用程序实例吗

1 个答案:

答案 0 :(得分:1)

新窗口会弹出,因为每次调用OnSave时都会创建一个新的Shell对象。您需要get the parent Shell window

Shell parentShell = Window.GetWindow(this) as Shell;