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

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

相关推荐
脚踏实地皮皮晨21 小时前
003002004_WPF Panel 基类 官方类定义
开发语言·windows·算法·c#·wpf·visual studio
湿滑路面1 天前
Rouyan:使用WPF/C#构建的基于LLM的快捷翻译小工具
开发语言·c#·wpf
软萌萌的11 天前
C#中的多级缓存架构设计与实现深度解析
缓存·c#·wpf
dalong102 天前
WPF:3D正八面体自动旋转
3d·wpf
仙宇觉尘2 天前
WPF Stylet可以如何实现导航功能?
java·开发语言·wpf
丙氨酸長鏈2 天前
WPF 引用 ASP.NET Core 的 AOT 版本
后端·asp.net·wpf
Xin_ye100862 天前
第六章:破局——WPF内存泄漏解决方案
c#·wpf
FuckPatience2 天前
WPF Button Content 的StringFormat
java·前端·wpf
dalong103 天前
WPF:3D正四面体旋转改错
3d·wpf
dalong104 天前
WPF:3D正四面体自动旋转
3d·wpf