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;
    }
}

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

相关推荐
玉面小君2 天前
从 WPF 到 Avalonia 的迁移系列实战篇6:ControlTheme 和 Style区别
c#·wpf·avalonia
c#上位机2 天前
wpf之Border
c#·wpf
SunflowerCoder2 天前
WPF迁移avalonia之图像处理(一)
图像处理·wpf·avalonia
周杰伦fans2 天前
WPF中的DataContext以及常见的绑定方式
wpf
没有bug.的程序员3 天前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
somethingGoWay3 天前
wpf 自定义输入ip地址的文本框
wpf
秋月的私语3 天前
Wpf程序屏幕居中问题修复全记录
wpf
我要打打代码3 天前
WPF启动窗体的三种方式
wpf
R瑾安3 天前
mysql集群部署(Mysql Group Replication)
数据库·mysql·wpf
c#上位机3 天前
wpf中资源的使用
c#·wpf