我通常会这样做:
public static class FocusOnVisibleBehavior
{
public static readonly DependencyProperty FocusProperty = DependencyProperty.RegisterAttached(
"Focus",
typeof(bool),
typeof(FocusOnVisibleBehavior),
new PropertyMetadata(false, OnFocusChange));
public static void SetFocus(DependencyObject source, bool value)
{
source.SetValue(FocusProperty, value);
}
public static bool GetFocus(DependencyObject source)
{
return (bool)source.GetValue(FocusProperty);
}
private static void OnFocusChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as FrameworkElement;
DependencyPropertyChangedEventHandler handler = (sender, args) =>
{
if ((bool)args.NewValue)
{
// see http://stackoverflow.com/questions/13955340/keyboard-focus-does-not-work-on-text-box-in-wpf
element.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate()
{
element.Focus(); // Set Logical Focus
Keyboard.Focus(element); // Set Keyboard Focus
//element.SelectAll();
}));
}
};
if (e.NewValue != null)
{
if ((bool)e.NewValue)
{
element.IsVisibleChanged += handler;
element.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
{
element.Focus(); // Set Logical Focus
Keyboard.Focus(element); // Set Keyboard Focus
//element.SelectAll();
}));
}
else
{
element.IsVisibleChanged -= handler;
}
}
// e.OldValue is never null because it's initialized to false via the PropertyMetadata()
// Hence, the effect here is that regardless of the value that's set, we first add the
// handler and then immediately remove it.
//if (e.NewValue != null)
//{
// element.IsVisibleChanged += handler;
// element.Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate ()
// {
// element.Focus(); // Set Logical Focus
// Keyboard.Focus(element); // Set Keyboard Focus
// //element.SelectAll();
// }));
//}
//if (e.OldValue != null)
// element.IsVisibleChanged -= handler;
}
不记得我是自己写的还是从其他地方得到的,不管你是这样使用的:
<TextBox behaviors:FocusOnVisibleBehavior.Focus="True" ... etc ... />