Bind behavior to all text fields in Silverlight

Can I attach behavior to all text blocks in a Silverlight application?

I need to add simple functions to all text fields. (select all text in the focus event)

void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e) { Target.SelectAll(); } 
+6
source share
1 answer

You can override the default style for TextBoxes in your application. Then in this style you can use some approach to apply the behavior with the installer (usually using attached properties).

It will be something like this:

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

Implementation of the behavior:

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

And an attached property to help us apply the behavior:

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

All Articles