You need to enable JavaScript to run this app. 如何为SfNavigationDrawer实现支持视图切换的Prism RegionAdapter
优惠活动
大模型
产品
解决方案
定价
更多

如何为SfNavigationDrawer实现支持视图切换的Prism RegionAdapter

问题原因

你当前只监听了region.Views.CollectionChanged事件,该事件仅在视图首次被添加到Region集合时触发。当切换已加载过的视图时,视图已经存在于Views集合中,只会触发ActiveViews集合的变化,不会触发你绑定的事件,因此ContentView没有更新。

修复代码

public class SfNavigationDrawerRegionAdapter : RegionAdapterBase<SfNavigationDrawer>
{
    public SfNavigationDrawerRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory)
    {
    }

    protected override void Adapt(IRegion region, SfNavigationDrawer regionTarget)
    {
        if (region == null)
        {
            throw new ArgumentNullException(nameof(region));
        }

        if (regionTarget == null)
        {
            throw new ArgumentNullException(nameof(regionTarget));
        }

        // 统一处理视图更新逻辑
        void UpdateContentView()
        {
            if (region.ActiveViews.OfType<FrameworkElement>().FirstOrDefault() is { } activeView)
            {
                regionTarget.ContentView = activeView;
            }
        }

        // 监听激活视图变化,覆盖首次添加和二次切换所有场景
        region.ActiveViews.CollectionChanged += (s, e) => UpdateContentView();
        // 初始化时处理已存在的视图
        UpdateContentView();
    }

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

代码说明

  • 改为监听ActiveViews.CollectionChanged事件,不管是首次新增的视图还是已加载过的视图被激活,都会触发该事件
  • 封装独立的视图更新方法,同时处理初始化时已有视图的场景
  • 由于你使用的是SingleActiveRegion,同一时间只会有一个激活视图,直接取第一个激活的视图赋值给ContentView即可满足需求

内容的提问来源于stack exchange,提问作者Geoffrey Migliacci

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 07:24:09