Attach behaviour to all TextBoxes in Silverlight

时间秒杀一切 提交于 2019-12-21 04:54:15

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/13498216/attach-behaviour-to-all-textboxes-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!