我喜欢使用附加行为。这是我在获得焦点时在文本框中选择值的示例。这样您就可以将此行为应用于任何文本框。附加行为的一大优点是许多属性/事件位于 UIElement 级别,因此您可以跨多个控件重用某些行为。无论如何,这是我的例子:
行为
public class SelectAllOnFocusedBehavior
{
private static bool GetSelectAllOnFocused(TextBox textBox)
{
return (bool) textBox.GetValue(SelectAllOnFocusedProperty);
}
public static void SetSelectAllOnFocused(
TextBox textBox, bool value)
{
textBox.SetValue(SelectAllOnFocusedProperty, value);
}
public static readonly DependencyProperty SelectAllOnFocusedProperty =
DependencyProperty.RegisterAttached(
"SelectAllOnFocused",
typeof (bool),
typeof (SelectAllOnFocusedBehavior),
new UIPropertyMetadata(false, OnSelectAllOnFocusedChanged));
private static void OnSelectAllOnFocusedChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
TextBox item = depObj as TextBox;
if (item == null)
return;
if (e.NewValue is bool == false)
return;
if ((bool) e.NewValue)
{
item.PreviewMouseLeftButtonDown += item_IgnoreLeftMouseDown;
item.GotFocus+=item_GotFocus;
}
else
{
//remove EventsHere
item.PreviewMouseLeftButtonDown -= item_IgnoreLeftMouseDown;
item.GotFocus -= item_GotFocus;
}
}
static void item_IgnoreLeftMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// Find the TextBox
DependencyObject parent = e.OriginalSource as UIElement;
while (parent != null && !(parent is TextBox))
parent = VisualTreeHelper.GetParent(parent);
if (parent != null)
{
var textBox = (TextBox)parent;
if (!textBox.IsKeyboardFocusWithin)
{
// If the text box is not yet focussed, give it the focus and
// stop further processing of this click event.
textBox.Focus();
e.Handled = true;
}
}
}
static void item_GotFocus(object sender, RoutedEventArgs e)
{
var item = e.OriginalSource as TextBox;
if (item != null)
item.SelectAll();
}
//EventHandler Here
}
对应的wpf
<TextBox x:Name="blahblah"
cmds:SelectAllOnFocusedBehavior.SelectAllOnFocused="True"
cmds:NextTabItemOnEnterBehavior.NextTabItemOnEnter="True"
Height="20" Width="75"