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

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

相关推荐
Java Fans13 小时前
在WPF项目中集成Python:Python.NET深度实战指南
python·.net·wpf
布伦鸽20 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
code bean2 天前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
沉到海底去吧Go2 天前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
lph19722 天前
自定义事件wpf
wpf
code bean2 天前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf
碎碎念的安静3 天前
WPF可拖拽ListView
c#·wpf
界面开发小八哥3 天前
界面组件DevExpress WPF中文教程:Grid - 如何识别行和卡片?
.net·wpf·界面控件·devexpress·ui开发
TwilightLemon4 天前
WPF 使用CompositionTarget.Rendering实现平滑流畅滚动的ScrollViewer,支持滚轮、触控板、触摸屏和笔
wpf
Vae_Mars6 天前
WPF中自定义消息弹窗
wpf