Attach behaviour to all TextBoxes in Silverlight
Asked Answered
S

1

6

Is it possible to attach behavior to all TextBoxes in Silverlight application?

I need to add simple functionality to all text boxes. (select all text on focus event)

 void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e)
    {
        Target.SelectAll();
    }
Semitropical answered 21/11, 2012 at 16:56 Comment(0)
B
8

You can override the default style for TextBoxes in your app. Then in this style, you can use some approach to apply a behavior with a setter (generally using attached properties).

It would something like this:

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

The behavior implementation:

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 the 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);
        }
    }
}
Barneybarnhart answered 21/11, 2012 at 17:4 Comment(1)
What is TextBoxSelectAllOnFocusBehaviorExtensionFormulaic

© 2022 - 2024 — McMap. All rights reserved.