在 Silverlight 中为所有文本框附加行为

6

在Silverlight应用程序中,是否可以为所有的TextBox附加行为?

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

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

8
您可以覆盖应用程序中文本框的默认样式。然后,在此样式中,您可以使用一些方法通过设置器来应用行为(通常使用附加属性)。
示例如下:
<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);
        }
    }
}

1
TextBoxSelectAllOnFocusBehaviorExtension是什么? - Peter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接