2009-01-28 51 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