我是WPF的新手。 我在我的窗口上有15个网格,我有一个小菜单,我可以点击它,选择要显示或隐藏的网格。一次只有一个网格。当我点击 Esc 时,我希望该网格能够显示(淡出)。我已经拥有了所有的动画,我只需要知道目前哪个网格可见(活动)。
我不知道如何获得当前最重要的窗口控件。
我的解决方案是在我的Window上触发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"));
}
}
答案 0 :(得分: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
}
}
这将消除代码隐藏中代码的需要。