2012-11-21 22 views
6

Ist es möglich, an alle TextBoxen in der Silverlight-Anwendung ein Verhalten anzuhängen?Verhalten an alle TextBoxen in Silverlight anhängen

Ich muss einfache Funktionalität zu allen Textfeldern hinzufügen. (wählen Sie den gesamten Text auf Fokus-Ereignis)

void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e) 
    { 
     Target.SelectAll(); 
    } 

Antwort

8

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); 
     } 
    } 
} 
+0

Ops hatte ich eingeschlossen das falsche Verhalten. Jetzt behoben! –

+0

Was ist 'TextBoxSelectAllOnFocusBehaviorExtension' – Peter