【问题标题】:Is there any way of checking if a DataGrid in Silverlight has Focus?有什么方法可以检查 Silverlight 中的 DataGrid 是否有焦点?
【发布时间】:2009-02-26 11:53:13
【问题描述】:

我有一个 Silverlight DataGrid,我需要检查它是否有焦点。我知道有一种方法可以为 GotFocus 设置焦点和事件,但看不到任何检查它是否有焦点的方法。

有什么想法吗?

【问题讨论】:

    标签: silverlight datagrid


    【解决方案1】:

    AFAIK 没有直接的方法或属性来检查它是否有焦点,但你应该能够使用 FocusManager.GetFocusedElement()。

    如果你随后定义了一个扩展方法,你应该可以调用 MyDataGrid.HasFocus():

    public static class ControlExtensions
    {
        public static bool HasFocus(this Control aControl)
        {
            return System.Windows.Input.FocusManager.GetFocusedElement() == aControl;
        }
    }
    

    [已编辑:我现在确实测试过:] 但是有一个问题:调用 GetFocusedElement() 可以返回 DataGrid 中当前聚焦的单元格。因此,在这种情况下,HasFocus 将返回 false。

    为了能够检查 DataGrid 或其一个单元格是否被聚焦,我们可以像这样调整我们的扩展方法

    public static class ControlExtensions
    {
        public static bool HasFocus(this Control aControl, bool aCheckChildren)
        {
            var oFocused = System.Windows.Input.FocusManager.GetFocusedElement() as DependencyObject;
            if (!aCheckChildren)
                return oFocused == aControl;
            while (oFocused != null)
            {
                if (oFocused == aControl)
                    return true;
                oFocused = System.Windows.Media.VisualTreeHelper.GetParent(oFocused);
            }
            return false;
        }
    }
    

    希望这会有所帮助?

    【讨论】:

    • @Tjipke 我遇到了类似的问题,但你的解决方案对我不起作用 - GetFocusedElement() 需要一个 DependcyObject 作为参数。您是否尝试过您发布的来源?
    • 是的,我确实尝试了我的源代码 :-) GetFocusedElement 的 silverlight 版本不需要该参数(请参阅:msdn.microsoft.com/en-us/library/cc190472(VS.95).aspx),但是 WPF 版本需要。你在WPF中尝试吗?在这种情况下,您不需要此代码,您可以使用 DataGrid.IsFocused
    猜你喜欢
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 2014-05-03
    • 2011-01-17
    • 1970-01-01
    • 2021-10-30
    • 2013-01-18
    • 2015-08-19
    相关资源
    最近更新 更多