【问题标题】:Silverlight C# WP - Listing attributes names of a classSilverlight C# WP - 列出类的属性名称
【发布时间】:2012-04-25 21:43:21
【问题描述】:

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

<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 

感激不尽。

【问题讨论】:

  • 你的 DaysOfWeek 应该是一个枚举,然后你应该在另一个类中有一个 DaysOfWeek 类型的 CurrentDay 属性

标签: c# silverlight windows-phone-7 xaml


【解决方案1】:

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

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);
}

【讨论】:

  • 可能会使用一个转换器来获取类型并返回它的公共属性列表。
【解决方案2】:

我的解决方案:

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;

简单易懂!

【讨论】:

    【解决方案3】:

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

    祝你好运;)

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2014-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多