textBox1.LostFocus += new RoutedEventHandler(textBox1_LostFocus);//获焦点是GotFocus textBox2.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(textBox2_GotKeyboardFocus);//仅键盘操作的失焦的事件,有下面的例子中有用到
二:键盘操作获焦时,其中text被全选中:
1.写个附加属性,然后就可以在Style里面用了
View Code
public class TextBoxHelper
{
public static readonly DependencyProperty AutoSelectAllProperty =
DependencyProperty.RegisterAttached("AutoSelectAll", typeof(bool), typeof(TextBoxHelper),
new FrameworkPropertyMetadata((bool)false,
new PropertyChangedCallback(OnAutoSelectAllChanged)));
public static bool GetAutoSelectAll(TextBoxBase d)
{
return (bool)d.GetValue(AutoSelectAllProperty);
}
public static void SetAutoSelectAll(TextBoxBase d, bool value)
{
d.SetValue(AutoSelectAllProperty, value);
}
private static void OnAutoSelectAllChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBox = d as TextBoxBase;
if (textBox != null)
{
var flag = (bool)e.NewValue;
if (flag)
{
textBox.GotFocus += TextBoxOnGotFocus;
}
else
{
textBox.GotFocus -= TextBoxOnGotFocus;
}
}
}
private static void TextBoxOnGotFocus(object sender, RoutedEventArgs e)
{
var textBox = sender as TextBoxBase;
if (textBox != null)
{
textBox.SelectAll();
}
}
}
然后在Style里面
<Setter Property="local:TextBoxHelper.AutoSelectAll" Value="True"/>
local是你引用的命名空间
<Setter Property="local:TextBoxHelper.AutoSelectAll" Value="True"/>
local是你引用的命名空间