Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huoxudong125/d048f9442e20f6f48cda22205d55cf43 to your computer and use it in GitHub Desktop.
Save huoxudong125/d048f9442e20f6f48cda22205d55cf43 to your computer and use it in GitHub Desktop.
Add support in PRISM for setting header of TabControl
namespace Coolblue.Wpf.Toolkit.Regions
{
public interface IRegionHostedInTabControlAware
{
string Header { get; }
}
}
using System.Collections;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using Coolblue.Wpf.Toolkit.Regions.RegionBehaviours.Helpers;
using Prism.Regions;
using Prism.Regions.Behaviors;
namespace Coolblue.Wpf.Toolkit.Regions.RegionBehaviours
{
public class RegionHostedInTabControlAwareBehavior : RegionBehavior, IHostAwareRegionBehavior
{
public const string BEHAVIOR_KEY = "RegionHostedInTabControlAwareBehavior";
private readonly ViewModelFromViewExtractor _viewModelFromViewExtractor;
private TabControl _hostTabControl;
public RegionHostedInTabControlAwareBehavior()
{
_viewModelFromViewExtractor = new ViewModelFromViewExtractor();
}
public DependencyObject HostControl { get; set; }
protected override void OnAttach()
{
_hostTabControl = HostControl as TabControl;
if(_hostTabControl != null)
{
if(_hostTabControl.IsLoaded)
ApplyTabControlAwareToTabItems(Region.Views);
else
_hostTabControl.Loaded += (s, e) => ApplyTabControlAwareToTabItems(Region.Views);
Region.Views.CollectionChanged += RegionViewsOnCollectionChanged;
}
}
private void RegionViewsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action == NotifyCollectionChangedAction.Add)
ApplyTabControlAwareToTabItems(e.NewItems);
}
private void ApplyTabControlAwareToTabItems(IEnumerable newRegionViews)
{
foreach(var newRegionView in newRegionViews)
{
var tabControlAware = newRegionView as IRegionHostedInTabControlAware;
if(tabControlAware != null)
ApplyTabControlAwareToTabItem(newRegionView, tabControlAware);
else
{
tabControlAware =
_viewModelFromViewExtractor.TryExtract(newRegionView) as IRegionHostedInTabControlAware;
if(tabControlAware != null)
ApplyTabControlAwareToTabItem(newRegionView, tabControlAware);
}
}
}
private void ApplyTabControlAwareToTabItem(object newRegionView,
IRegionHostedInTabControlAware tabControlAware)
{
if(_hostTabControl.IsLoaded)
{
var tabItemHostingRegion = GetTabItem(newRegionView);
tabItemHostingRegion.Header = tabControlAware.Header;
}
}
private TabItem GetTabItem(object tabControlAwareRegion)
{
return (TabItem)_hostTabControl.ItemContainerGenerator.ContainerFromItem(tabControlAwareRegion);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment