Я пытаюсь написать метод расширения, который позволит мне сфокусироваться на элементе управления. Я написал метод ниже, который работает нормально, однако, если элемент управления уже загружен, то, очевидно, подключение события Loaded
не будет никакого смысла - мне также нужен способ проверить, был ли элемент управления загружен, так что Я могу просто запустить код Focus()
, не подключая событие.
Можно ли имитировать свойство IsLoaded
в элементе управления?
public static void SetFocus(this Control control)
{
// return if the control is not visible
if (control.Visibility == Visibility.Collapsed) { return; }
control.Loaded += (sender, routedeventArgs) =>
{
// focus the Silverlight plugin first
System.Windows.Browser.HtmlPage.Plugin.Focus();
control.IsTabStop = true; // required to allow Focus
control.Focus();
if (control is TextBox)
{
((TextBox)control).SelectAll();
}
};
}
РЕДАКТИРОВАТЬ: В соответствии с ответом ColinE ниже, я реализовал это так:
public static void SetFocus(this Control control)
{
// return if the control is not visible
if (control.Visibility == Visibility.Collapsed) { return; }
if (control.Descendants().Count() > 0)
{
// already loaded, just set focus and return
SetFocusDelegate(control);
return;
}
// not loaded, wait for load before setting focus
control.Loaded += (sender, routedeventArgs) =>
{
SetFocusDelegate(control);
};
}
public static void SetFocusDelegate(Control control)
{
// focus the Silverlight plugin first
System.Windows.Browser.HtmlPage.Plugin.Focus();
control.IsTabStop = true; // required to allow Focus
control.Focus();
if (control is TextBox)
{
((TextBox)control).SelectAll();
}
}