问题
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