WPF使用ContentControl控件实现区域导航,并使用Prism依赖注入优化

背景:使用ContentControl控件实现区域导航是有Mvvm框架的WPF都能使用的,不限于Prism

主要是将ContenControl控件的Content内容在ViewModel中切换成不同的用户控件

下面是MainViewModel:

cs 复制代码
private object body;

public object Body
{
    get { return body; }
    set { body = value; RaisePropertyChanged(); }
}


public DelegateCommand<string> OpenCommand { get; set; }

public MainWindowViewModel()
{
    OpenCommand = new DelegateCommand<string>(obj =>
    {
        Body = obj switch
        {
            "ViewA" => new ViewA(),
            "ViewB" => new ViewB(),
            "ViewC" => new ViewC(),
            _ => Body
        };
    });
}

上面是有Mvvm框架就行了,每次打开新的模块就创建一个用户控件对象

下面是使用Prism框架的导航实现会方便一些

1.首先在App.xaml.cs中注入用户控件的依赖

2.ContentControl中的Content修改为:

XML 复制代码
<ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" />

3.MainWindowViewModel变成:

cs 复制代码
public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager regionManager;

    public DelegateCommand<string> OpenCommand { get; set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        OpenCommand = new DelegateCommand<string>(obj => { regionManager.Regions["ContentRegion"].RequestNavigate(obj); });
        this.regionManager = regionManager;
    }
}

-- 也就是由创建用户控件,变成调用依赖注入的用户控件

相关推荐
故事不长丨13 小时前
WPF MvvmLight 超详细使用教程
c#·wpf·mvvm·mvvmlight
IT小哥哥呀2 天前
基于windows的个人/团队的时间管理工具
windows·c#·wpf·时间管理
sczmzx2 天前
Cefsharp.WPF高分辨率下崩溃问题解决方案
wpf
cjp5603 天前
023.WPF combox控件数据绑定
wpf
Scout-leaf3 天前
WPF新手村教程(七)—— 终章(MVVM架构初见杀)
c#·wpf
极客智造3 天前
WPF DataGrid 多选绑定 + 强类型命令回调 通用解决方案
wpf
ZoeJoy83 天前
机器视觉C# 调用相机:从 USB 摄像头到海康工业相机(WinForms & WPF)
数码相机·c#·wpf
ALex_zry4 天前
C++高性能日志与监控系统设计
c++·unity·wpf
zhojiew4 天前
使用flink agent框架实现流式情感分析的示例
大数据·flink·wpf
海盗12344 天前
ScottPlot在WPF的基本使用和中文乱码问题
c#·.net·wpf