让textbox获焦、失焦事件,获焦时,其text被选中
一:让textbox获焦、失焦事件:
1 2 | 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是你引用的命名空间
转载请注明出处。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步