你写个附加属性,然后就可以在Style里面用了。
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里面
local是你引用的命名空间
背景色的变化,可以在IsFocused事件中写。 至于输入完成后textBox失去焦点,可以textbox接收到回车按键事件和失去焦点这个两个事件中,将焦点转移到其他的Element上去。 例如 Grid.IsFocusable = true; Grid.GetFocus(); Grid.IsFocusable = false;