WPF TextBox MaxLength — Is there any way to bind this to the Data Validation Max Length on the bound field?

前端 未结 5 644
北海茫月
北海茫月 2020-12-14 23:27

ViewModel:

public class MyViewModel
{
    [Required, StringLength(50)]
    public String SomeProperty { ... }
}

XAML:



        
5条回答
  •  情话喂你
    2020-12-14 23:51

    I used a Behavior to connect the TextBox to its bound property's validation attribute (if any). The behavior looks like this:

    /// 
    /// Set the maximum length of a TextBox based on any StringLength attribute of the bound property
    /// 
    public class RestrictStringInputBehavior : Behavior
    {
        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:

    
            
                
            
        
    
    
    

    You could also add this functionality by extending TextBox, but I like using behaviors because they are modular.

提交回复
热议问题