This seems like a workaround to do this, since WPF does not support this attribute, and so you will enter the attributes in the view model and the view model will look for them. They can be in any internal format.
In any case, here is a demonstration of the problem, as you stated about it. We add the Descriptions property to the class to which the text fields are bound. This property is a dictionary that maps property names to descriptions, i.e. Attributes In the static constructor for the view model, we look through all the attributes and fill out the dictionary.
A small XAML file with two text fields:
<Grid > <StackPanel> <TextBox Text="{Binding FirstName}" ToolTip="{Binding Descriptions[FirstName]}"/> <TextBox Text="{Binding LastName}" ToolTip="{Binding Descriptions[LastName]}"/> </StackPanel> </Grid>
code:
DataContext = new DisplayViewModel();
and a rudimentary representation model with two properties:
public class DisplayViewModel { private static Dictionary<string, string> descriptions; static DisplayViewModel() { descriptions = new Dictionary<string,string>(); foreach (var propertyName in PropertyNames) { var property = typeof(DisplayViewModel).GetProperty(propertyName); var displayAttributes = property.GetCustomAttributes(typeof(DisplayAttribute), true); var displayAttribute = displayAttributes.First() as DisplayAttribute; var description = displayAttribute.Name; descriptions.Add(propertyName, description); } } public DisplayViewModel() { FirstName = "Bill"; LastName = "Smith"; } public static IEnumerable<string> PropertyNames { get { return new[] { "FirstName", "LastName" }; } } [Display(Name = "First Name")] public string FirstName { get; set; } [Display(Name = "Last Name")] public string LastName { get; set; } public IDictionary<string, string> Descriptions { get { return descriptions; } } }
source share