wpf中,如何让textbox获得焦点时,其text被选中?
展开全部
你写个附加属性,然后就可以在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里面
<Setter Property="local:TextBoxHelper.AutoSelectAll" Value="True"/>
local是你引用的命名空间
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是你引用的命名空间
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询