WPF并将ToolTip绑定到DisplayAttribute

时间:2011-04-20 02:41:47

标签: wpf binding

在我的视图模型中,我已将DisplayAttributes添加到我的属性中,现在想将TextBox控件的ToolTip属性绑定到DisplayAttribute的Description属性。

我发现this SO question处理描述的读取,但无法弄清楚如何使用计算的描述填充工具提示。

1 个答案:

答案 0 :(得分: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; } }
}