Prism基础知识 学习(一)Region
Prism基础知识 学习(一)Region
首先如果不采用Prism 的方法,这个案例我们该怎么写:
首先在MainWindow.cs中
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition />
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button
Margin="10"
Command="{Binding OPenCommand}"
CommandParameter="ViewA"
Content="打开模块A" />
<Button
Margin="10"
Command="{Binding OPenCommand}"
CommandParameter="ViewB"
Content="打开模块B" />
<Button
Margin="10"
Command="{Binding OPenCommand}"
CommandParameter="ViewC"
Content="打开模块C" />
</StackPanel>
<ContentControl Grid.Row="1" Content="{Binding Body}" />
</Grid>
然后在ViewA.xml中编写,ViewB.xml,ViewC.xml同理
<TextBlock FontSize="60" Text="我是模块A" />
在MainWindowViewModel.cs中写
public class MainWindowViewModel : BindableBase
{
private string _title = "Prism Application";
public DelegateCommand<string> OPenCommand { get; set; }
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private object body;
public object Body
{
get { return body; }
set
{
body = value;
RaisePropertyChanged();
}
}
public MainWindowViewModel()
{
OPenCommand = new DelegateCommand<string>(Open);
}
private void Open(string obj)
{
switch (obj)
{
case "ViewA": Body = new ViewA(); break;
case "ViewB": Body = new ViewB(); break;
case "ViewC": Body = new ViewC(); break;
}
}
}
- 首先MainWindow中的button绑定了OPenCommand委托,传入了CommandParameter参数。
- 在MainWindowViewModel中,声明了DelegateCommand
OPenCommand { get; set; }委托,然后该委托调用了Open()方法。 - 这个方法打开ViewA等窗体。窗体打开在ContentControl控件中。
这种写法的不足在哪里?
- 如果后续需要打开的View窗体变多,就需要不断的维护MainWindowViewModel与MainWindow文件。
基于Prism的写法(依赖注入)(动态添加实例)
修改ContentControl组件,这里修改为prism:RegionManager.RegionName
<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion"/>
然后在App.xml中注册
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<ViewA>();
containerRegistry.RegisterForNavigation<ViewB>();
containerRegistry.RegisterForNavigation<ViewC>();
}
然后在MainWindowViewModel.xaml中,添加regionManager。修改初始化方法,绑定regionManager。
主要是修改Open方法,不再需要使用switch来进行选择
private readonly IRegionManager regionManager;
public MainWindowViewModel(IRegionManager regionManager)
{
OPenCommand = new DelegateCommand<string>(Open);
this.regionManager = regionManager;
}
private void Open(string obj)
{
regionManager.Regions["ContentRegion"].RequestNavigate(obj);
}