Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting initial control focus in Silverlight

I'm looking for a way to automatically set the initial focus on a Silverlight UserControl to a specific control. I have a login page with a user name textbox and I'd like to have it so that as soon as the user goes to the page their cursor is already positioned and waiting in the username textbox instead of having to make them click the box.

I tried calling .Focus in the UserControl's Loaded event but with no success. Anyone know how to do this?

like image 858
Nick Gotch Avatar asked Jul 14 '09 16:07

Nick Gotch


2 Answers

public MainPage()
{
    InitializeComponent();

    this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    HtmlPage.Plugin.Focus();
    MyTextBox.Focus();
}
like image 185
Kiril Stanoev Avatar answered Sep 23 '22 02:09

Kiril Stanoev


I whipped up a quick SL3 app and it is difficult to have the initial focus go to the UserControl let alone to a control within the Silverlight control.

However, see if this solution solves this issue for you. You'll have to use a little JavaScript.

Here's the code for reference:

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
    TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" style="height:100%;">
<head runat="server">
    <title>Test Page For TextFocusTest</title>
    <script type="text/javascript">
    window.onload = function()
        {
            document.getElementById('Xaml1').focus();
        }
    </script>
</head>
<body style="height:100%;margin:0;">
    <form id="form1" runat="server" style="height:100%;">
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div  style="height:100%;">
            <asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/TextFocusTest.xap" Version="2.0" Width="100%" Height="100%" />
        </div>
    </form>
</body>
</html>

Once your SL control has focus, you can further set the focus to a specific control using something like:

namespace SilverlightApplication2
{
    public partial class MainPage : UserControl
    {
        public MainPage ()
        {
            InitializeComponent ();

            this.GotFocus += new RoutedEventHandler (MainPage_GotFocus);
        }

        void MainPage_GotFocus (object sender, RoutedEventArgs e)
        {
            uxLogin.Focus ();
        }
    }
}

where uxLogin is defined in XAML as:

<TextBox x:Name="uxLogin" Height="25" Width="100" />
like image 29
Scott Marlowe Avatar answered Sep 26 '22 02:09

Scott Marlowe