WPF TextBox MaxLength -- 有没有办法将其绑定到绑定字段上的数据验证最大长度? [英] WPF TextBox MaxLength -- Is there any way to bind this to the Data Validation Max Length on the bound field?

查看:63
本文介绍了WPF TextBox MaxLength -- 有没有办法将其绑定到绑定字段上的数据验证最大长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视图模型:

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

XAML:

<TextBox Text="{Binding SomeProperty}" MaxLength="50" />

有什么方法可以避免设置 TextBox 的 MaxLength 以匹配我的 ViewModel(由于它在不同的程序集中可能会发生变化)并让它根据 StringLength 要求自动设置最大长度?

Is there any way to avoid setting the MaxLength of the TextBox to match up my ViewModel (which could change since it is in a different assembly) and have it automatically set the max length based on the StringLength requirement?

推荐答案

我使用了一个 行为 将 TextBox 连接到其绑定属性的验证属性(如果有).行为如下所示:

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

/// <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;
                }
            }
        }
    }
}

您可以看到,该行为只是检索文本框的数据上下文及其文本"的绑定表达式.然后它使用反射来获取StringLength"属性.用法是这样的:

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>

您也可以通过扩展 TextBox 来添加此功能,但我喜欢使用行为,因为它们是模块化的.

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

这篇关于WPF TextBox MaxLength -- 有没有办法将其绑定到绑定字段上的数据验证最大长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆