2012-11-21 21 views
6

是否可以将行为附加到Silverlight应用程序中的所有文本框?将行为附加到Silverlight中的所有文本框

我需要为所有文本框添加简单的功能。 (选择对焦点事件的所有文字)

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

回答

8

您可以覆盖的默认样式在您的应用程序文本框。然后以这种风格,你可以使用一些方法来使用setter来应用行为(通常使用附加属性)。

这将是这样的:

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

行为实现:

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

而且附加属性,以帮助我们的行为:

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

行动,我已经列入错误的行为。现在修好! –

+0

什么是“TextBoxSelectAllOnFocusBehaviorExtension” – Peter