WPF文本框MAXLENGTH - 有什么办法来绑定这数据有效性最大长度上绑定字段? [英] WPF TextBox MaxLength -- Is there any way to bind this to the Data Validation Max Length on the bound field?

查看:1612
本文介绍了WPF文本框MAXLENGTH - 有什么办法来绑定这数据有效性最大长度上绑定字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视图模型:

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

XAML:

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

有什么办法可避免设置文本框到我的视图模型(这可能会改变匹配的MaxLength因为它是一个不同的装配),并自动设置基础上,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?

推荐答案

下面是另一个方法,工作得很好...

Here is another approach that works pretty well ...

我用的行为来连接文本框的绑定属性的验证属性(如果有的话)。行为看起来是这样的:

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>

您也可以通过扩展文本框,但我喜欢使用行为,因为它们是模块化的。

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

这篇关于WPF文本框MAXLENGTH - 有什么办法来绑定这数据有效性最大长度上绑定字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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