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);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本