在Silverlight中设置初始控制焦点

Nic*_*tch 8 .net silverlight xaml silverlight-2.0

我正在寻找一种方法来自动将Silverlight UserControl的初始焦点设置为特定控件.我有一个登录页面与用户名的文本框,我想有它,这样一旦用户进入页面的光标已经定位,并在用户名文本框等,而不必让他们点击文本框.

我尝试在UserControl的Loaded事件中调用.Focus,但没有成功.有人知道怎么做吗?

Kir*_*oev 16

public MainPage()
{
    InitializeComponent();

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

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    HtmlPage.Plugin.Focus();
    MyTextBox.Focus();
}
Run Code Online (Sandbox Code Playgroud)


Sco*_*owe 5

我刮起了快速SL3应用程序,它很难有初始焦点转到用户控件更不用说Silverlight控件内的控制.

但是,请查看此解决方案是否为您解决了此问题.你必须使用一点JavaScript.

这是参考的代码:

<%@ 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>
Run Code Online (Sandbox Code Playgroud)

SL控件具有焦点后,您可以使用以下内容进一步将焦点设置为特定控件:

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 ();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

其中uxLogin在XAML中定义为:

<TextBox x:Name="uxLogin" Height="25" Width="100" />
Run Code Online (Sandbox Code Playgroud)