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

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

相关推荐
beyond谚语1 天前
第一章 WPF概述
wpf
necessary6532 天前
从工行“余额归零”事件看CAP定理:当金融系统在一致性与可用性之间做出选择
分布式·金融·wpf·可用性测试
棉晗榜2 天前
WPF隐藏控件后,怎么让其上部的控件空间自动撑高
wpf
壹佰大多3 天前
【Redisson分布式锁源码分析-3】
数据结构·分布式·mysql·spring·spring cloud·wpf·lua
LateFrames3 天前
以小白视角尝试 WPF / WinUI3 / MAUI / MAUI Blazor 构建 Windows 桌面程序
windows·wpf·maui·mauiblazor·winui3
偶尔的鼠标人4 天前
Avalonia/WPF 打开子窗口,并且跨页面传值
c#·wpf·mvvm·avalonia
玖笙&4 天前
✨WPF编程进阶【6.1】:图形原则(附源码)
c++·c#·wpf·visual studio
lixy5794 天前
WPF检测网络状态切换
wpf
纸照片4 天前
WPF中为Button设置IsMouseOver和IsPressed事件中改变背景颜色不起作用
c#·.net·wpf
Aevget4 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(四)
ui·.net·wpf·devexpress·wpf控件