protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (Interaction.AllowKeyDown(e))
{
if (e.Handled)
{
return;
}
// We ignore the Control modifier key because it is used
// specifically for scrolling which is implemented in the
// TreeView. We do not mark the event handled if Control is
// pressed so that it will bubble up to the parent TreeView of
// this item.
switch (e.Key)
{
// WPF merges the behavior for the Left and Right keys
// because they behave logically with respect to flow
// direction (which isn't available in Silverlight)
case Key.Left:
// The Left key will collapse an expanded item or
// move to the parent if the item is already
// collapsed.
if (!TreeView.IsControlKeyDown && CanExpandOnInput && IsExpanded)
{
if (FocusManager.GetFocusedElement() != this)
{
Focus();
}
else
{
IsExpanded = false;
}
e.Handled = true;
}
break;
case Key.Right:
// The Right key is only useful when the item has
// children
if (!TreeView.IsControlKeyDown && CanExpandOnInput)
{
// Expand the item if it is collapsed or move into
// the first child if it is already expanded.
if (!IsExpanded)
{
UserInitiatedExpansion = true;
IsExpanded = true;
e.Handled = true;
}
else if (HandleDownKey())
{
e.Handled = true;
}
}
break;
case Key.Up:
if (!TreeView.IsControlKeyDown && HandleUpKey())
{
e.Handled = true;
}
break;
case Key.Down:
if (!TreeView.IsControlKeyDown && HandleDownKey())
{
e.Handled = true;
}
break;
case Key.Add:
if (CanExpandOnInput && !IsExpanded)
{
UserInitiatedExpansion = true;
IsExpanded = true;
e.Handled = true;
}
break;
case Key.Subtract:
if (CanExpandOnInput && IsExpanded)
{
IsExpanded = false;
e.Handled = true;
}
break;
}
}
// Because Silverlight's ScrollViewer swallows many useful key
// events (which it can ignore on WPF if you override
// HandlesScrolling or use an internal only variable in
// Silverlight), the root TreeViewItems explicitly propagate KeyDown
// events to their parent TreeView.
if (IsRoot)
{
TreeView parent = ParentTreeView;
if (parent != null)
{
parent.PropagateKeyDown(e);
}
}
}