wpf问题---如何让textbox获得焦点时,其text被选中。

2025-02-23 05:17:34
推荐回答(2个)
回答1:

你写个附加属性,然后就可以在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是你引用的命名空间

回答2:

背景色的变化,可以在IsFocused事件中写。 至于输入完成后textBox失去焦点,可以textbox接收到回车按键事件和失去焦点这个两个事件中,将焦点转移到其他的Element上去。 例如 Grid.IsFocusable = true; Grid.GetFocus(); Grid.IsFocusable = false;