How to add view to a PRISM TabControl region WITHOUT making it selected?

天涯浪子 提交于 2020-01-26 02:22:49

问题


We have a WPF application using PRISM, with a region of type TabControl.

    <TabControl prism:RegionManager.RegionName="{x:Static inf:RegionNames.ContentRegion}">
        <TabControl.ItemContainerStyle>
            <Style TargetType="{x:Type TabItem}">
                <Setter Property="Header" Value="{Binding TabName}" />
            </Style>
        </TabControl.ItemContainerStyle>
    </TabControl>

And we are registering views with

_regionManager.RegisterViewWithRegion(RegionNames.ContentRegion, typeof(ContentView));

Problem is, this way the registered tab automatically gets selected. Is there a way to add a view as tab but NOT select it??


回答1:


The solution I came up with is to implement an interface for each view, and implement a custom RegionAdapter which uses it.

Note: This interface also allows you to specify tab order, if you need it as well.

public interface ITabItemView
{
    int TabItemIndex { get; }

    bool IsStartupTab { get; }
}

public class TabControlRegionAdapter : RegionAdapterBase<TabControl>
{
    private ITabItemView startupTab = null;

    public TabControlRegionAdapter(IRegionBehaviorFactory factory)
        : base(factory)
    {

    }

    protected override void Adapt(IRegion region, TabControl regionTarget)
    {
        region.Views.CollectionChanged += (s, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    var items = regionTarget.Items;

                    foreach (ITabItemView tab in e.NewItems)
                    {
                        if (tab.TabItemIndex > items.Count)
                            items.Add(tab);
                        else
                            items.Insert(tab.TabItemIndex, tab);

                        if (tab.IsStartupTab)
                        {
                            if (tab != startupTab && startupTab != null)
                                throw new InvalidOperationException("More than one tab is the startup tab.");

                            startupTab = tab;

                            regionTarget.SelectedItem = tab;
                        }
                    }
                }
            };
    }

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

And of course in your Bootstrapper class you need

protected override Microsoft.Practices.Prism.Regions.RegionAdapterMappings ConfigureRegionAdapterMappings()
    {
        var mappings = base.ConfigureRegionAdapterMappings();
        mappings.RegisterMapping(typeof(TabControl), Container.Resolve<TabControlRegionAdapter>());
        return mappings;
    }


来源:https://stackoverflow.com/questions/30071300/how-to-add-view-to-a-prism-tabcontrol-region-without-making-it-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!