0

我是 WPF 的新手。我的窗口上有 15 个网格,我有一个小菜单,我可以在上面单击并选择要显示或隐藏的网格。一次只有一个网格。当我点击 . 时,我希望该网格隐藏(淡出)Esc。我已经有了所有的动画,我只需要知道现在什么网格是可见的(活动的)。

我不知道如何获得对我的窗口的当前最高控制权。

我的解决方案是KeyDown在我的 Window 上触发事件时:

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"));
        }

    }
4

1 回答 1

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
    }
}

这将消除在代码隐藏中包含代码的需要。

于 2009-01-28T08:04:48.720 回答