相信各位都有在开发过程中遇到需要将类里面的属性映射成控件的需求,在传统做法上,一般是将对应的类绑定到ItemControl控件中,并通过绑定的方式绑定对应的属性值
这样的做法没问题,但是如果类的属性发生了更改,则需要重新进行类的绑定,这样的操作比较麻烦,如果能够实现类的属性自动映射成控件,则后续类的属性变更的时候则可以不再更改控件样式,只是添加类的属性即可
问题是,类映射成控件,需要绑定属性值以及属性类型,直接通过属性列表的方式绑定也比较麻烦,我们只需要知道属性类型,属性值,以及属性名称就可以生成自定义控件
所以最后我通过在类内部新建一个包含属性信息的列表用来存储属性值信息以供绑定。如下
public class PropertySetting : NotifyPropertyChanged
{
private string propertyName;
public string PropertyName
{
get { return propertyName; }
set { Set(ref propertyName, value); }
}
private Type propertyType;
public Type PropertyType
{
get { return propertyType; }
set { Set(ref propertyType, value); }
}
private object propertyValue;
public object PropertyValue
{
get { return propertyValue; }
set { Set(ref propertyValue, value); }
}
}
这里为了进行绑定,继承了 NotifyPropertyChanged接口,在此不在赘述
PropertySetting 用于存储属性的相关信息,我们需要在类实例化后,将PropertySetting的列表存到类中,这里我以Student类示例
public class Student : NotifyPropertyChanged
{
private int age;
public int Age
{
get { return age; }
set { Set(ref age, value); }
}
private string studentName;
public string StudentName
{
get { return studentName; }
set { Set(ref studentName, value); }
}
private double gradePercent;
public double GradePercent
{
get { return gradePercent; }
set { Set(ref gradePercent, value); }
}
private Dictionary<string, string> grades;
public Dictionary<string, string> Grades
{
get { return grades; }
set { Set(ref grades, value); }
}
private DateTime birthday;
public DateTime Birthday
{
get { return birthday; }
set { Set(ref birthday, value); }
}
private ObservableCollection<PropertySetting> infos;
[JsonIgnore]
public ObservableCollection<PropertySetting> Infos
{
get
{
return infos;
}
set { Set(ref infos, value); }
}
}
这里在Student类内部添加了Infos属性,用于存储类相关信息以供绑定
在类实例化后需要将对应的属性值添加到属性列表中,这里需要应用反射获取类的属性值,属性类型,以及属性名称,所以在上面的PropertySetting 类中我添加了静态类获取传入的类的属性值并输出属性信息集合,静态方法如下
static public ObservableCollection<PropertySetting> GetTypeInfo<T>(T pro) where T : class
{
ObservableCollection<PropertySetting> temp = new ObservableCollection<PropertySetting>();
var pros = pro.GetType().GetProperties();
foreach (var item in pros)
{
if (item.Name == "Infos") continue;
temp.Add(new PropertySetting() { PropertyName = item.Name, PropertyType = item.PropertyType, PropertyValue = item.GetValue(pro) });
}
return temp;
}
在类实例化后再通过静态方法获取对应的属性信息列表并添加到类的infos中,下面是实例化的过程
var student = new Student()
{
Age = i,
StudentName = "名字" + i,
Grades = new Dictionary<string, string> { { "语文", "10" }, {


2688

被折叠的 条评论
为什么被折叠?



