加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将行为附加到Silverlight中的所有TextBox

发布时间:2020-12-15 08:13:40 所属栏目:百科 来源:网络整理
导读:是否可以将行为附加到Silverlight应用程序中的所有TextBox? 我需要为所有文本框添加简单的功能. (选择焦点事件上的所有文字) void Target_GotFocus(object sender,System.Windows.RoutedEventArgs e) { Target.SelectAll(); } 解决方法 您可以覆盖应用中Tex
是否可以将行为附加到Silverlight应用程序中的所有TextBox?

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

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

解决方法

您可以覆盖应用中TextBoxes的默认样式.然后在这种风格中,您可以使用某种方法将行为应用于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);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读