绑定到属性

tor*_*ros 9 c# data-binding wpf xaml

我有课

public class Car {

    [Description("name of the car")]
    public string Name { get; set; }

    [Description("age of the car")]
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

是否有可能将Description属性绑定到Label内容.我正在寻找的解决方案不应该要求实例化Class对象.

H.B*_*.B. 9

它不是一个正确的绑定(无论如何都不是静态数据所必需的)但你可以轻松创建一个MarkupExtension来检索它,只需传递类型和属性名称并通过反射获取它.

大纲将是这样的:

public Type Type { get; set; }
public string PropertyName { get; set; }

ProvideValue: Type.GetProperty(PropertyName)
                  .GetCustomAttributes(true)
                  .OfType<DescriptionAttribute>()
                  .First()
                  .Description
Run Code Online (Sandbox Code Playgroud)
<!-- Usage example -->
Text="{me:Description Type=local:Car, PropertyName=Name}"
Run Code Online (Sandbox Code Playgroud)

  • 我很矛盾 - 你正在向他展示一种方法,但是你也让他能够创建属于Mordor深处的代码...... (5认同)