zoukankan      html  css  js  c++  java
  • 限制WPF textbox 字符最大值

    /// <summary>
    /// Set the maximum length of a TextBox based on any StringLength attribute of the bound property
    /// </summary>
    public class RestrictStringInputBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            AssociatedObject.Loaded += (sender, args) => setMaxLength();
            base.OnAttached();
        }
    
        private void setMaxLength()
        {
            object context = AssociatedObject.DataContext;
            BindingExpression binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
    
            if (context != null && binding != null)
            {
                PropertyInfo prop = context.GetType().GetProperty(binding.ParentBinding.Path.Path);
                if (prop != null)
                {
                    var att = prop.GetCustomAttributes(typeof(StringLengthAttribute), true).FirstOrDefault() as StringLengthAttribute;
                    if (att != null)
                    {
                        AssociatedObject.MaxLength = att.MaximumLength;
                    }
                }
            }
        }
    }
    You can see, the behavior simply retrieves the data context of the text box, and its binding expression for "Text". Then it uses reflection to get the "StringLength" attribute. Usage is like this:
    <UserControl
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    
        <TextBox Text="{Binding SomeProperty}">
            <i:Interaction.Behaviors>
                <local:RestrictStringInputBehavior />
            </i:Interaction.Behaviors>
        </TextBox>
    
    </UserControl>
    

      

    <UserControl
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    
        <TextBox Text="{Binding SomeProperty}">
            <i:Interaction.Behaviors>
                <local:RestrictStringInputBehavior />
            </i:Interaction.Behaviors>
        </TextBox>
    
    </UserControl>
    

      

  • 相关阅读:
    本学期的学习计划
    snmp 学习记录
    解锁树莓派root账号
    树莓派通过阿里云内网穿透,搭建下载机
    golang Ordered Map
    go 切片slice奇怪的地方
    学习scons总结
    go语言学习小结
    学习git版本管理工具
    轻松记账工程冲刺第二阶段10
  • 原文地址:https://www.cnblogs.com/canyuexingchen/p/8110320.html
Copyright © 2011-2022 走看看