我正在尝试将初始焦点设置为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。
我知道其他人已经创造了行为等等来完成这项任务,但我想知道为什么这样做不起作用。
答案 0 :(得分: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;
}
}
(在某些情况下,您可能需要根据this link调用ApplyTemplate)