在做一个例子是需要运行起来后焦点默认设置在密码框上,在网上查了资料
自己找到一种方法,此方法在oob模式下管用
public Login() { InitializeComponent(); txtLoginName.Text = "admin"; // 设置焦点在密码框上 Dispatcher.BeginInvoke(() => { txtLoginPwd.Focus(); }); }
网上找到的另一种方法
1.想在Silverlight首次启动让某个文本框获取焦点,使用Loaded事件中txt.Focus()是不起做用的,要完成这功能只要添加一句代码即可:
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e) { HtmlPage.Plugin.Invoke("focus"); txtName.Focus(); }
2.在程序中为了方便用户,在一个文本框中按回车后跳到别一个文本框或其它控件,我们可以对原有的TextBox进行扩充,添加一个NextControl的属性用于保存下一个控件的名字,
另外为了方便我加了一个ToNextControl的事件,这样用起来更加方便,代码如下:
namespace HahaMan.SLTools.Controls { public class MyTextBox:TextBox { //事件 public event EventHandler ToNextControl; private string nextControl=""; //用于保存下一个控件的名字 public string NextControl { get { return nextControl; } set { nextControl = value; } } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Key == Key.Enter)//如果是回车 { if (ToNextControl != null)//如果自己写了事件处理程序 { ToNextControl(this, e);//调用事件 } else { //如果没有指定事件 if (nextControl != null && nextControl.Length > 0) { //查找下一个控件 Control c = (this.Parent as Panel).FindName(nextControl) as Control; if (c != null) { c.Focus(); } } } } } } }
使用方法一:
<my:MyTextBox Height="23" HorizontalAlignment="Left" Margin="786,152,0,0" Name="txtName" <span style="color:#ff0000;">NextControl="txtPwd"</span> VerticalAlignment="Top" Width="120" /> <my:MyTextBox Height="23" HorizontalAlignment="Left" Margin="786,205,0,0" Name="txtPwd" <span style="color:#ff0000;">NextControl="btnLogin"</span> VerticalAlignment="Top" Width="120" /> <Button Content="登录" Height="23" Margin="763,259,0,0" Name="btnLogin" VerticalAlignment="Top" HorizontalAlignment="Left" Width="56" Click="btnLogin_Click" />
使用方法二:
xaml代码:
<my:MyTextBox Height="23" HorizontalAlignment="Left" Margin="786,152,0,0" Name="txtName" VerticalAlignment="Top" Width="120" <span style="color:#ff0000;">ToNextControl="toNextControl"</span> /> <my:MyTextBox Height="23" HorizontalAlignment="Left" Margin="786,205,0,0" Name="txtPwd" VerticalAlignment="Top" Width="120" <span style="color:#ff0000;">ToNextControl="toNextControl"</span> /> <Button Content="登录" Height="23" Margin="763,259,0,0" Name="btnLogin" VerticalAlignment="Top" HorizontalAlignment="Left" Width="56" Click="btnLogin_Click" />
cs代码:
private void toNextControl(object sender, EventArgs e) { if (sender == txtName) txtPwd.Focus(); if (sender == txtPwd) btnLogin.Focus(); }
网上找的方法转载至 http://blog.csdn.net/lijun7788/article/details/8087773
Silverlight 密码框 Focus,布布扣,bubuko.com
原文:http://www.cnblogs.com/ZJ199012/p/3725052.html