gpt4 book ai didi

c# - 使用代码从 ViewModel 绑定(bind)控件中检索 System.ComponentModel.DataAnnotations.DisplayAttribute 属性

转载 作者:太空宇宙 更新时间:2023-11-03 14:31:58 26 4
gpt4 key购买 nike

我注意到 SL3 验证器在创建验证消息时会自动使用 DisplayAttribute 中的属性。我对有关如何使用代码从控件绑定(bind)中提取此信息的任何建议感兴趣。我已经包括了一个例子:

View 模型代码:

[Display(Name="First Name")]
public string FirstName { get; set; }

我知道可以在逐个控制的基础上执行类似以下操作(在本例中为 TextBox)来实现此目的:

BindingExpression dataExpression = _firstNameTextBox.GetBindingExpression(TextBox.TextProperty)
Type dataType = dataExpression.DataItem.GetType();
PropertyInfo propInfo = dataType.GetProperty(dataExpression.ParentBinding.Path.Path);
DisplayAttribute attr = propInfo.GetCustomAttributes(false).OfType<DisplayAttribute>().FirstOrDefault();
return (attr == null) ? dataExpression.ParentBinding.Path.Path : attr.Name;

我很感兴趣是否有任何方法可以通用地执行此操作,而无需知道特定类型的控件。

提前感谢您的任何想法!!

最佳答案

好问题。不幸的是,虽然您可以硬编码一些属性并且非常安全,但实际上没有办法通用地做到这一点。例如ContentControl.ContentProperty、TextBlock.TextProperty、TextBox.TextProperty等。

Silverlight 中的 DataForm 做同样的事情。我还重新实现了他们使用的名为 GetPropertyByPath 的简单辅助方法。它基本上完成您的代码所做的,除了它可以走多步属性路径。它不能访问索引属性,但 DataForm 也不能,所以它至少和那一样好。

从那时起,获取 DisplayAttribute 就像您所显示的那样。

public static PropertyInfo GetPropertyByPath( object obj, string propertyPath )
{

ParameterValidation.ThrowIfNullOrWhitespace( propertyPath, "propertyPath" );

if ( obj == null ) {
return null;
} // if

Type type = obj.GetType( );

PropertyInfo propertyInfo = null;
foreach ( var part in propertyPath.Split( new char[] { '.' } ) ) {

// On subsequent iterations use the type of the property
if ( propertyInfo != null ) {
type = propertyInfo.PropertyType;
} // if

// Get the property at this part
propertyInfo = type.GetProperty( part );

// Not found
if ( propertyInfo == null ) {
return null;
} // if

// Can't navigate into indexer
if ( propertyInfo.GetIndexParameters( ).Length > 0 ) {
return null;
} // if

} // foreach

return propertyInfo;

}

关于c# - 使用代码从 ViewModel 绑定(bind)控件中检索 System.ComponentModel.DataAnnotations.DisplayAttribute 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2398657/

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