gpt4 book ai didi

c# - WPF TextBox MaxLength——有没有办法将其绑定(bind)到绑定(bind)字段上的数据验证最大长度?

转载 作者:可可西里 更新时间:2023-11-01 09:00:29 26 4
gpt4 key购买 nike

View 模型:

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

XAML:

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

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

最佳答案

我用了 Behavior将 TextBox 连接到其绑定(bind)属性的验证属性(如果有)。行为看起来像这样:

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

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

<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 来添加此功能,但我喜欢使用行为,因为它们是模块化的。

关于c# - WPF TextBox MaxLength——有没有办法将其绑定(bind)到绑定(bind)字段上的数据验证最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8745325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com