我遇到一些问题让Silverlight 4将初始焦点设置在一个控件上,最大的问题是如果控件没有渲染焦点则无法保证。
答案 0 :(得分:2)
我创建了一个行为,它将焦点设置在Loaded
事件中,以确保加载控件。
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace xxx.Behaviors
{
public class SetControlFocusBehavior : Behavior<Control>
{
protected override void OnAttached()
{
base.OnAttached();
if (AssociatedObject is Control)
{
((Control)AssociatedObject).Loaded += new RoutedEventHandler(SetControlFocusBehavior_Loaded);
}
}
void SetControlFocusBehavior_Loaded(object sender, RoutedEventArgs e)
{
var control = sender as Control;
if (control == null)
{
return;
}
System.Windows.Browser.HtmlPage.Plugin.Focus();
control.Focus();
}
protected override void OnDetaching()
{
base.OnDetaching();
((Button)AssociatedObject).Loaded -= SetControlFocusBehavior_Loaded;
}
}
}
要使用它,只需使用Blend将其拖放到控件上。
<TextBox x:Name="MyTextBox">
<i:Interaction.Behaviors>
<sg:SetControlFocusBehavior/>
</i:Interaction.Behaviors>
</TextBox>