2011-04-20 92 views

回答

1

这似乎是一种迂回的方式来做到这一点,因为WPF不支持此属性,这样你会进入属性到视图模型和视图模型会找他们。他们可以采用任何内部格式。

在任何情况下,这里是问题的一个演示,你已经说了。我们将Descriptions属性添加到文本框绑定到的类。该属性是一个将属性名称映射到描述的字典,即属性。在视图模型的静态构造函数中,我们查找所有属性并填充字典。

有两个文本框一个小XAML文件:

<Grid > 
    <StackPanel> 
     <TextBox Text="{Binding FirstName}" ToolTip="{Binding Descriptions[FirstName]}"/> 
     <TextBox Text="{Binding LastName}" ToolTip="{Binding Descriptions[LastName]}"/> 
    </StackPanel> 
</Grid> 

隐藏代码:

 DataContext = new DisplayViewModel(); 

和基本的视图模型具有两个属性:

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; } } 
} 
+0

这一工程很好,谢谢! DisplayAttribute公开两个属性,名称(这对于UI)和描述(描述名称),这是我使用的工具提示(我在考虑使用名称的标签是什么,但是这意味着你失去了设计时值的名字,这是不值得的麻烦)。如果你要使用说明,一定要使用GetDescription()来读它,因为它会评估任何使用资源字符串(通过的ResourceType属性)。 – 2011-04-26 23:52:46