Silverlight C# WP - 列出类的属性名称

本文关键字:属性 WP Silverlight | 更新日期: 2023-09-27 18:32:11

如何通过绑定列出类的所有属性名称

<ListBox>
<TextBlock Name="{Binding WHAAAAT???!}" />
</ListBox>

类:

public class DaysOfWeek
{    
    public bool Monday {get; set;}
    public bool Tuesday { get; set; }
    public bool Wednesday { get; set; }
    public bool Thursday { get; set; }
    public bool Friday { get; set; }
    public bool Saturday { get; set; }
    public bool Sunday { get; set; }
}

我想将此内容放在列表框中。请帮我解决这个问题。

Monday
Tuesday
Wednesday 
Thursday 
Friday 
Saturday
Sunday 

感激。

Silverlight C# WP - 列出类的属性名称

听起来你需要使用反射,如下所示

using System.Reflection;  // reflection namespace
// get all public static properties of MyClass type
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
                                              BindingFlags.Static);
// sort properties by name
Array.Sort(propertyInfos,
        delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
        { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
// write property names
foreach (PropertyInfo propertyInfo in propertyInfos)
{
  Console.WriteLine(propertyInfo.Name);
}

我的解决方案:

Classes.DaysOfWeek _DaysOfWeek;
_DaysOfWeek = new Classes.DaysOfWeek();
var listProp = _DaysOfWeek.GetType().GetProperties().ToList();
List<String> newList = new List<String>{};
foreach(var item in listProp){
newList.Add(item.Name);
}
listBox_Days.ItemsSource = newList;

容易理解!

查看 MVVM 模型(通过创建新的全景/透视/数据绑定示例应用程序的示例)这是在尝试编写新代码时减少最多时间的模型,同时保持非常干净。

祝你好运;)