1、将App.xaml中的StartupUri="MainWindow.xaml"删除。
2、使用NuGet安装Prism.Wpf、Prism.Core、Prism.Unity。
3、添加类“Bootstrapper”,编辑如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using Microsoft.Practices.Unity; 8 using Prism.Unity; 9 using ViewInjection.Views;10 11 namespace ViewInjection12 {13 public class Bootstrapper:UnityBootstrapper14 {15 protected override DependencyObject CreateShell()16 {17 return Container.Resolve();18 }19 20 protected override void InitializeShell()21 {22 Application.Current.MainWindow.Show();23 }24 }25 }
4、创建文件夹Views,将MainWindow.xaml移动到此文件夹中。向Views文件夹中添加TextA.xaml。
110 11 12 1413
1 using System.Windows.Navigation; 2 using System.Windows.Shapes; 3 using Microsoft.Practices.Unity; 4 using Prism.Regions; 5 6 namespace ViewInjection.Views 7 { 8 ///9 /// MainWindow.xaml 的交互逻辑10 /// 11 public partial class MainWindow : Window12 {13 private IUnityContainer _container;14 private IRegionManager _regionManager;15 public MainWindow(IUnityContainer unityContainer, IRegionManager regionManager)16 {17 InitializeComponent();18 19 _container = unityContainer;20 _regionManager = regionManager;21 }22 23 24 private void BtnAddRegion_OnClick(object sender, RoutedEventArgs e)25 {26 var view = _container.Resolve();27 IRegion region = _regionManager.Regions["ContentRegion"];28 region.Add(view);29 }30 }31 }
19 10 1211
5、修改App.xaml
1 using System; 2 using System.Collections.Generic; 3 using System.Configuration; 4 using System.Data; 5 using System.Linq; 6 using System.Threading.Tasks; 7 using System.Windows; 8 9 namespace ViewInjection10 {11 ///12 /// App.xaml 的交互逻辑13 /// 14 public partial class App : Application15 {16 protected override void OnStartup(StartupEventArgs e)17 {18 base.OnStartup(e);19 20 var bootstrapper=new Bootstrapper();21 bootstrapper.Run();22 }23 24 }25 }