2009-01-28 91 views
0

我是WPF的新手。 我的窗口上有15个网格,我有一个小菜单,我可以点击并选择要显示或隐藏的网格。一次只能有一个网格。当我击中Esc时,我希望这个网格可以(淡出)。我已经拥有了所有的动画,我只需要知道当前网格是否可见(活动)。使用ESC键隐藏网格

我不知道如何获得当前我的窗口的最高控制权。在触发我的窗口KeyDown事件

我的解决办法是:

private void Window_KeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
    { 
     if (e.Key == System.Windows.Input.Key.Escape) 
     { 
      //check all grids for IsVisible and on the one that is true make 
      BeginStoryboard((Storyboard)this.FindResource("theVisibleOne_Hide")); 
     } 

    } 

回答

1

通过积极的,我认为是指具有键盘焦点之一。如果是这样,下面将返回当前拥有键盘输入焦点的控件:

System.Windows.Input.Keyboard.FocusedElement 

你可以使用这样的:

if (e.Key == System.Windows.Input.Key.Escape) 
{ 
    //check all grids for IsVisible and on the one that is true make 
    var selected = Keyboard.FocusedElement as Grid; 
    if (selected == null) return; 

    selected.BeginStoryboard((Storyboard)this.FindResource("HideGrid")); 
} 

会更解耦的方法是创建一个静态附加的依赖属性。它可以像这样(未经)使用:

<Grid local:Extensions.HideOnEscape="True" .... /> 

一个非常粗略的实现将是这样的:

public class Extensions 
{ 
    public static readonly DependencyProperty HideOnEscapeProperty = 
     DependencyProperty.RegisterAttached(
      "HideOnEscape", 
      typeof(bool), 
      typeof(Extensions), 
      new UIPropertyMetadata(false, HideOnExtensions_Set)); 

    public static void SetHideOnEscape(DependencyObject obj, bool value) 
    { 
     obj.SetValue(HideOnEscapeProperty, value); 
    } 

    public static bool GetHideOnEscape(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(HideOnEscapeProperty); 
    } 

    private static void HideOnExtensions_Set(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var grid = d as Grid; 
     if (grid != null) 
     { 
      grid.KeyUp += Grid_KeyUp; 
     } 
    } 

    private static void Grid_KeyUp(object sender, KeyEventArgs e) 
    { 
     // Check for escape key... 
     var grid = sender as Grid; 
     // Build animation in code, or assume a resource exists (grid.FindResource()) 
     // Apply animation to grid 
    } 
} 

这将消除需要有代码的代码隐藏。

+0

保罗,非常感谢! – Ivan 2009-01-28 11:34:47