2012-11-21 15 views
6

È possibile allegare il comportamento a tutti i TextBox in un'applicazione Silverlight?Allegare il comportamento a tutti i TextBox in Silverlight

Ho bisogno di aggiungere funzionalità semplici a tutte le caselle di testo. (selezionare tutto il testo in caso di messa a fuoco)

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

risposta

8

è possibile ignorare lo stile predefinito per TextBoxes nella vostra app. Quindi, in questo stile, è possibile utilizzare un approccio per applicare un comportamento con un setter (generalmente utilizzando le proprietà associate).

Si sarebbe qualcosa di simile:

<Application.Resources> 
    <Style TargetType="TextBox"> 
     <Setter Property="local:TextBoxEx.SelectAllOnFocus" Value="True"/> 
    </Style> 
</Application.Resources> 

L'implementazione comportamento:

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(); 
    } 
} 

E la proprietà associata per aiutarci ad applicare il comportamento:

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, mi aveva incluso il comportamento sbagliato Risolto ora! –

+0

Che cos'è 'TextBoxSelectAllOnFocusBehaviorExtension'? – Peter