前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >Prism region in tabcontrol

Prism region in tabcontrol

作者头像
JusterZhu
发布2025-01-23 20:30:28
发布2025-01-23 20:30:28
7200
代码可运行
举报
文章被收录于专栏:JusterZhuJusterZhu
运行总次数:0
代码可运行

1.概要

有小伙伴向我提问,在使用Prism开发WPF的时候会遇到TabControl作为Region容器的场景。那么会遇到如下问题:

  • 默认加载需要显示多个View且每个View不一样
  • 每个TabItem页面可以控制隐藏或显示
  • 每个TabItem的Header需要跟显示的View名称一样
  • 程序运行后可以动态添加新的View
  • 代码简洁,不要有很多曲线救国的事情发生

其实遇到的以上问题,Prism框架中已有对应的解决方案。但是大家在网络上搜索的时候大部分都会搜到没什么用的内容容易造成开发时间的浪费。接下来我将提供一小段示例代码讲解思路,后续遇到问题可以举一反三。

2.详细内容

2.1 View

下面定义了一个TabControl,和三个控制按钮用于演示显示、隐藏、动态添加。

MainWindow.xaml

代码语言:javascript
代码运行次数:0
复制
<Window x:Class="PrismTableDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PrismTableDemo"
        xmlns:prism="http://prismlibrary.com/"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Button Content="add" Width="80" Height="30" Margin="1" Name="BtnAdd" Click="BtnAdd_OnClick"></Button>
            <Button Content="remove" Width="80" Height="30" Margin="1" Name="BtnRemove" Click="BtnRemove_OnClick"></Button>
            <Button Content="show view C" Name="BtnShowViewC" Click="BtnShowViewC_OnClick"></Button>
        </StackPanel>
        <TabControl Grid.Row="1" prism:RegionManager.RegionName="TabRegion" />
    </Grid>
</Window>

MainWindow.cs文件内容。

代码语言:javascript
代码运行次数:0
复制
using System.Windows;
using PrismTableDemo.Views;

namespace PrismTableDemo;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private readonly IRegionManager _regionManager;
    
    public MainWindow(IRegionManager regionManager)
    {
        InitializeComponent();
        _regionManager = regionManager;
        //注册默认需要显示的View
        _regionManager.RegisterViewWithRegion("TabRegion", typeof(ViewA));
        _regionManager.RegisterViewWithRegion("TabRegion", typeof(ViewB));
        DataContext = this;
    }

    private void BtnRemove_OnClick(object sender, RoutedEventArgs e)
    {
        var region = _regionManager.Regions["TabRegion"];
        var view = region.Views.FirstOrDefault(v => v.GetType() == typeof(ViewA));
        if (view != null)
        {
            //隐藏ViewA
            region.Remove(view);
        }
    }

    private void BtnAdd_OnClick(object sender, RoutedEventArgs e)
    {
        //显示已有的ViewA
        _regionManager.RegisterViewWithRegion("TabRegion", typeof(ViewA));
    }

    private void BtnShowViewC_OnClick(object sender, RoutedEventArgs e)
    {
        //运行起来之后,动态添加View C
        _regionManager.RegisterViewWithRegion("TabRegion", typeof(ViewC));
    }
}

ViewA.xaml

代码语言:javascript
代码运行次数:0
复制
<UserControl x:Class="PrismTableDemo.Views.ViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PrismTableDemo.Views"
             mc:Ignorable="d" Tag="ViewA"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="View A"/>
    </Grid>
</UserControl>

ViewB.xaml

代码语言:javascript
代码运行次数:0
复制
<UserControl x:Class="PrismTableDemo.Views.ViewB"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PrismTableDemo.Views"
             mc:Ignorable="d" Tag="ViewB"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="View B"/>
    </Grid>
</UserControl>

ViewC.xaml

代码语言:javascript
代码运行次数:0
复制
<UserControl x:Class="PrismTableDemo.Views.ViewC"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:PrismTableDemo.Views"
             mc:Ignorable="d" Tag="ViewC"
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <TextBlock Text="View C"></TextBlock>
    </Grid>
</UserControl>

2.2 App

代码语言:javascript
代码运行次数:0
复制
using System.Windows;
using System.Windows.Controls;

namespace PrismTableDemo;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry) { }


    protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog) { }
    
    protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
    {
        base.ConfigureRegionAdapterMappings(regionAdapterMappings);
        //这里是解决以上问题的关键点,稍后我们一起来看看实现是什么。自定义了TabControlRegionAdapter
        regionAdapterMappings.RegisterMapping(typeof(TabControl), Container.Resolve<TabControlRegionAdapter>());
    }
}

2.3 TabControlRegionAdapter

这里的RegionAdapterBase对象是解决问题的关键点,学习到这个概念就非常容易解决开篇提到的那些问题。RegionAdapterBase<T> 是 Prism 框架中用于区域适配的一个基类。区域适配器的主要作用是将特定类型的控件(例如 ContentControlItemsControl 等)转换为 Prism 区域,使其能够包含和管理视图。

作用

  1. 适配特定类型的控件: RegionAdapterBase<T> 专门用于适配特定类型的控件,以便这些控件能够作为 Prism 区域使用。
  2. 管理视图的添加和移除: 它提供了管理视图(如 UserControl)的添加和移除的机制。
  3. 区域行为管理: 可以定义和管理区域的行为(如激活、停用等),以便在区域中添加或移除视图时执行特定的操作。

应用场景

  1. 自定义控件适配: 当你有一个自定义的控件,需要将其转换为 Prism 区域时,可以通过继承 RegionAdapterBase<T> 来实现适配。
  2. 复杂布局管理: 在复杂的布局中,如果需要特定类型的容器来管理视图的显示和隐藏,可以使用区域适配器来简化这一过程。
  3. 动态视图加载: 在需要动态加载视图的应用程序中,区域适配器可以帮助你管理这些视图的生命周期。
  4. 模块化应用程序: 在模块化应用程序中,不同模块可能需要向不同类型的控件中添加视图,区域适配器提供了一种统一的方式来管理这些视图。
代码语言:javascript
代码运行次数:0
复制
using System.Windows.Controls;

namespace PrismTableDemo
{
    public class TabControlRegionAdapter : RegionAdapterBase<TabControl>
    {
        public TabControlRegionAdapter(IRegionBehaviorFactory factory) : base(factory)
        {
        }

        protected override void Adapt(IRegion region, TabControl regionTarget)
        {
            region.ActiveViews.CollectionChanged += (s, e) =>
            {
                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    foreach (var view in e.NewItems)
                    {
                        var tabItem = regionTarget.Items
                            .Cast<TabItem>()
                            .FirstOrDefault(i => i.Content == view);

                        if (tabItem != null)
                        {
                            tabItem.Visibility = System.Windows.Visibility.Visible;
                        }
                        else
                        {
                            tabItem = new TabItem
                            {
                                Content = view,
                                Header = ((UserControl)view).Tag
                            };

                            regionTarget.Items.Add(tabItem);
                        }
                    }
                }

                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                {
                    foreach (var view in e.OldItems)
                    {
                        var tabItem = regionTarget.Items
                            .Cast<TabItem>()
                            .FirstOrDefault(i => i.Content == view);

                        if (tabItem != null)
                        {
                            tabItem.Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                }
            };
        }

        protected override IRegion CreateRegion()
        {
            return new AllActiveRegion();
        }
    }
}

2.4 运行

默认启动运行效果

隐藏View A

显示ViewA并且动态添加View C。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2024-09-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 JusterZhu 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.概要
  • 2.详细内容
  • 2.1 View
  • 2.2 App
  • 2.3 TabControlRegionAdapter
  • 2.4 运行
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档