Skip to content

Instantly share code, notes, and snippets.

@Jalalx
Created April 22, 2015 12:44
Show Gist options
  • Save Jalalx/1015526a139933e4fb56 to your computer and use it in GitHub Desktop.
Save Jalalx/1015526a139933e4fb56 to your computer and use it in GitHub Desktop.
LoadAwareRegionBehavior raise ViewLoaded/ViewUnloaded methods when View.Loaded/View.Unloaded events raise.
using System;
namespace Microsoft.Practices.Prism.Regions
{
/// <summary>
/// Represent ILoadAware functionality for View-Model classes.
/// </summary>
public interface ILoadAware
{
/// <summary>
/// Gets called by RegionManager when associated View.Loaded event raise.
/// </summary>
void ViewLoaded();
/// <summary>
/// Gets called by RegionManager when associated View.Unloaded event raise.
/// </summary>
void ViewUnloaded();
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Microsoft.Practices.Prism.Regions
{
public class LoadAwareRegionBehavior : RegionBehavior
{
public const string BehaviorKey = "LoadAwareRegion";
protected override void OnAttach()
{
this.Region.Views.CollectionChanged += RegionActiveViewsChanged;
}
private void RegionActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Remove)
{
UnregisterEventHandlers(e.OldItems);
}
else if (e.Action == NotifyCollectionChangedAction.Add)
{
RegisterEventHandlers(e.NewItems);
}
}
private static void RegisterEventHandlers(IList views)
{
foreach (var view in views)
{
var frameworkElement = view as FrameworkElement;
if (frameworkElement != null)
{
var loadAwareDataContext = frameworkElement.DataContext as ILoadAware;
if (loadAwareDataContext != null)
{
frameworkElement.Loaded += (s, e) => loadAwareDataContext.ViewLoaded();
frameworkElement.Unloaded += (s, e) => loadAwareDataContext.ViewUnloaded();
}
}
}
}
private static void UnregisterEventHandlers(IList views)
{
foreach (var view in views)
{
var frameworkElement = view as FrameworkElement;
if (frameworkElement != null)
{
var loadAwareDataContext = frameworkElement.DataContext as ILoadAware;
if (loadAwareDataContext != null)
{
frameworkElement.Loaded -= (s, e) => loadAwareDataContext.ViewLoaded();
frameworkElement.Unloaded -= (s, e) => loadAwareDataContext.ViewUnloaded();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment