1

我正在尝试将初始焦点设置为 Silverlight 表单中的控件。我正在尝试使用附加属性,以便可以在 XAML 文件中指定焦点。我怀疑在控件准备好接受焦点之前设置焦点。任何人都可以验证这一点或建议如何使这项技术发挥作用吗?

这是我的 TextBox 的 XAML 代码

<TextBox x:Name="SearchCriteria" MinWidth="200" Margin ="2,2,6,2" local:AttachedProperties.InitialFocus="True"></TextBox>

该属性在 AttachedProperties.cs 中定义:

public static DependencyProperty InitialFocusProperty = 
    DependencyProperty.RegisterAttached("InitialFocus", typeof(bool), typeof(AttachedProperties), null);

public static void SetInitialFocus(UIElement element, bool value)
{
    Control c = element as Control;
    if (c != null && value)
        c.Focus();
}

public static bool GetInitialFocus(UIElement element)
{
    return false;
}

当我在 SetInitialFocus 方法中放置断点时,它会触发并且控件确实是所需的 TextBox,并且它确实调用了 Focus。

我知道其他人已经创造了行为等来完成这项任务,但我想知道为什么这不起作用。

4

1 回答 1

1

你是对的,控件还没有准备好接收焦点,因为它还没有完成加载。您可以添加它以使其工作。

public static void SetInitialFocus(UIElement element, bool value)
{
    Control c = element as Control;
    if (c != null && value)
    {
        RoutedEventHandler loadedEventHandler = null;
        loadedEventHandler = new RoutedEventHandler(delegate
        {
            // This could also be added in the Loaded event of the MainPage
            HtmlPage.Plugin.Focus();
            c.Loaded -= loadedEventHandler;
            c.Focus();
        });
        c.Loaded += loadedEventHandler;
    }
}

(在某些情况下,您可能还需要根据此链接调用 ApplyTemplate )

于 2010-12-17T16:57:07.430 回答