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

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

相关推荐
✎ ﹏梦醒͜ღ҉繁华落℘16 小时前
开发WPF项目时遇到的问题总结
wpf
hqwest2 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars2 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest2 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest2 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0073 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业6 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103586 天前
WPF之绑定!
c#·wpf
DataIntel6 天前
wpf问题记录
wpf
蓝点lilac7 天前
C# WPF 内置解码器实现 GIF 动图控件
c#·.net·wpf·图像