private static void OnIsExpandedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TreeViewItem source = d as TreeViewItem;
bool isExpanded = (bool) e.NewValue;
// Notify any automation peers of the expansion change
TreeViewItemAutomationPeer peer = FrameworkElementAutomationPeer.FromElement(source) as TreeViewItemAutomationPeer;
if (peer != null)
{
peer.RaiseExpandCollapseAutomationEvent((bool) e.OldValue, isExpanded);
}
// Raise the Expanded and Collapsed events
RoutedEventArgs args = new RoutedEventArgs();
if (isExpanded)
{
source.OnExpanded(args);
}
else
{
source.OnCollapsed(args);
}
if (isExpanded)
{
// Try to scroll the child TreeViewItems into view once we've
// finished expanding them. We do it immediately if there is
// no ExpansionStateGroup, or wait for the transition to finish
// if there is one.
if (source.ExpansionStateGroup == null && source.UserInitiatedExpansion)
{
source.UserInitiatedExpansion = false;
TreeView parent = source.ParentTreeView;
if (parent != null)
{
// Note that we scroll the entire TreeViewItem into
// view, not just its HeaderElement.
parent.ItemsControlHelper.ScrollIntoView(source);
}
}
}
else if (source.ContainsSelection)
{
// Select the this item if it collapsed the selected item
source.Focus();
}
}