WPF and ToolTip binding to DisplayAttribute attribute

In my view model, I added DisplayAttributes to my properties and now I would like to bind the ToolTip property of my TextBox controls to the Description property of DisplayAttribute.

I found this SO question that handles reading a description but cannot figure out how to populate a hint using a computed description.

+4
source share
1 answer

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; } } } 
+1
source

All Articles