DisplayAttribute name with a variable, Dynamic DisplayName

前端 未结 2 473
北海茫月
北海茫月 2021-01-18 05:03

Wondering if this is possible or something with this effect.

public class MyModel
{
    public string Name { get; set; }

    [Display(Name = String.Format(\         


        
2条回答
  •  生来不讨喜
    2021-01-18 05:34

    For purposes like internationalisation, you can subclass the key attributes like DisplayNameAttribute, DescriptionAttribute and CategoryAttribute, and use some lookup (resx, database, whatever). This works fine and it is easy to find examples.

    However, you cannot access values of the object, simply because: an attribute is not given that context!

    However, if this is for things like PropertyGrid, DataGridView etc, there is another approach: use either ICustomTypeDescriptor or TypeDescriptionProvider to provide a custom descriptor, which can specify the DisplayName it wants. You can capture the target object/property when you create the instance of the custom descriptor. If you only want to tweak the properties, sometimes TypeConverter can be simpler to implement than ICustomTypeDescriptor/TypeDescriptionProvider, but ultimately both need custom PropertyDescriptor implementations.

    This is all quite a bit of work; make sure you're happy with this level of complexity! There is probably a simpler option.

提交回复
热议问题