6

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

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

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

1 回答 1

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);
        }
    }
}
于 2012-11-21T17:04:46.543 回答