Restore System.ComponentModel.DataAnnotations.DisplayAttribute properties from controls associated with ViewModel using code

I noticed that SL3 Validators automatically use properties from DisplayAttribute when creating validation messages. I am interested in any suggestions on how to extract this information from a control binding using code. I gave an example:

ViewModel Code:

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

I know this can be achieved based on Control-by-Control by doing something like the following (TextBox in this case):

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;

I am wondering if there is any way to do this in the general case, without knowing the specific type of control.

Thanks in advance for any thoughts!

+3
source share
1
. , , . , ContentControl.ContentProperty, TextBlock.TextProperty, TextBox.TextProperty ..

DataForm Silverlight . , , 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;

}
+1

Source: https://habr.com/ru/post/1735844/


All Articles