c# wpf mvvm prism regionamanger 属性 在 Bootstrapper 中为 null

c# wpf mvvm prism regionamanger property is null in Bootstrapper

我正在尝试创建一个新的 WPF MVVM 棱镜项目,但是当我尝试在 shell 中向我的区域添加视图时,RegionManager 属性 出现空引用异常。有谁能够帮助我 ? 这是我的代码:

 class Bootstrapper : UnityBootstrapper
    {
        public IRegionManager regionManager { get; set; }
        public IRegionManager RegionManager
        {
            get
            {
                return regionManager;
            }
            set
            {
                regionManager = value;
            }
        }

        protected override DependencyObject CreateShell()
        {
            return new Shell();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();
            App.Current.MainWindow = (Window)this.Shell;
            App.Current.MainWindow.Show();
            this.RegionManager.RequestNavigate("MainRegion", new Uri("PartNumberView", UriKind.Relative));
        }

        protected override void ConfigureModuleCatalog()
        {
            base.ConfigureModuleCatalog();
        }
    }

shell xaml:

<Window x:Class="MechanicsPriceComparer.Shell"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prism="http://www.codeplex.com/prism"
        xmlns:local="clr-namespace:MechanicsPriceComparer"
        mc:Ignorable="d"
        Title="MechanicPriceComparer" Height="450" Width="800">
    <Grid>
        <ItemsControl Name="NameOfMainRegion" prism:RegionManager.RegionName="MainRegion" ></ItemsControl>
    </Grid>
</Window>

app.xaml:

protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            Bootstrapper bootstrapper = new Bootstrapper();
            bootstrapper.Run();
        }

您需要先初始化 RegionManager 属性,然后再使用它。

您的代码示例:

protected override void InitializeShell()
{
    base.InitializeShell();
    App.Current.MainWindow = (Window)this.Shell;
    App.Current.MainWindow.Show();

    RegionManager = Prism.Regions.RegionManager.GetRegionManager(Application.Current.MainWindow);

    this.RegionManager.RequestNavigate("MainRegion", new Uri("PartNumberView", UriKind.Relative));
}