Sie können den Standardstil für Textfelder in Ihrer Anwendung außer Kraft setzen. Dann können Sie in diesem Stil einen Ansatz verwenden, um ein Verhalten mit einem Setter anzuwenden (im Allgemeinen mit angehängten Eigenschaften).
Es wäre so etwas wie dieses:
<Application.Resources>
<Style TargetType="TextBox">
<Setter Property="local:TextBoxEx.SelectAllOnFocus" Value="True"/>
</Style>
</Application.Resources>
Das Verhalten Umsetzung:
public class TextBoxSelectAllOnFocusBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.GotMouseCapture += this.OnGotFocus;
this.AssociatedObject.GotKeyboardFocus += this.OnGotFocus;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.GotMouseCapture -= this.OnGotFocus;
this.AssociatedObject.GotKeyboardFocus -= this.OnGotFocus;
}
public void OnGotFocus(object sender, EventArgs args)
{
this.AssociatedObject.SelectAll();
}
}
Und die angefügten Eigenschaft, die uns helfen, das Verhalten gelten:
public static class TextBoxEx
{
public static bool GetSelectAllOnFocus(DependencyObject obj)
{
return (bool)obj.GetValue(SelectAllOnFocusProperty);
}
public static void SetSelectAllOnFocus(DependencyObject obj, bool value)
{
obj.SetValue(SelectAllOnFocusProperty, value);
}
public static readonly DependencyProperty SelectAllOnFocusProperty =
DependencyProperty.RegisterAttached("SelectAllOnFocus", typeof(bool), typeof(TextBoxSelectAllOnFocusBehaviorExtension), new PropertyMetadata(false, OnSelectAllOnFocusChanged));
private static void OnSelectAllOnFocusChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
var behaviors = Interaction.GetBehaviors(sender);
// Remove the existing behavior instances
foreach (var old in behaviors.OfType<TextBoxSelectAllOnFocusBehavior>().ToArray())
behaviors.Remove(old);
if ((bool)args.NewValue)
{
// Creates a new behavior and attaches to the target
var behavior = new TextBoxSelectAllOnFocusBehavior();
// Apply the behavior
behaviors.Add(behavior);
}
}
}
Ops hatte ich eingeschlossen das falsche Verhalten. Jetzt behoben! –
Was ist 'TextBoxSelectAllOnFocusBehaviorExtension' – Peter