通過積極的,我認爲是指具有鍵盤焦點之一。如果是這樣,下面將返回當前擁有鍵盤輸入焦點的控件:
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
}
}
這將消除需要有代碼的代碼隱藏。
保羅,非常感謝! – Ivan 2009-01-28 11:34:47