2016-12-06 37 views
-1

StudentViewModel对象的列表。我使用DataGridView绑定此列表,并根据绑定模型的属性将列生成设置为自动。C#LINQ,如果它有一个自定义选择属性特性

public async Task LoadGridView() 
    { 
     Tuple<List<StudentViewModel>, int> result = await App.StudentService.SearchAsync(studentRequestModel); 
     dataGridView1.DataSource = null; 
     dataGridView1.DataSource = result.Item1; 
    } 

在StudentViewModel,我已经装饰了一些具有自定义属性的属性IsViewable

[AttributeUsage(AttributeTargets.Property)] 
public class IsViewable: Attribute 
{ 
    public bool Value { get; set; } 
} 

用法:

 [IsViewable(Value = true)] 
     public string Name { get; set; } 

想法是,刚刚与UI控件绑定之前,我想过滤列表,让匿名对象的一个​​新的列表,以便我网将与填充只有选定的属性。

enter image description here

注:我不希望创建特定于电网单独视图模型。如果它造成性能问题,我会重构它。

+2

没有办法动态基因评价一个匿名类型,因为这些属性需要在编译时知道。您可以使用字典来映射名称和值,或填充“ExpandoObject”并使用“dynamic”来获取类似属性的语法。或者创建一个新的'o'并动态复制具有该属性的属性。 –

+0

这个答案可能会帮助:https://stackoverflow.com/a/4938442/1220550 –

+1

如果我理解正确的话,你不希望这些属性由'DataGridView'显示。如果这是你想要的,你不能通过使用属性'[Browsable(false)]'而不是你自定义的'IsViewable'来实现它吗? –

回答

0

美中不足的是,我序列化的动态列表,然后反序列化。然后我将这个动态列表绑定到datagridview上,它像一个魅力一样工作。

enter image description here

整个项目可以在这里找到foyzulkarim/GenericComponents

来电/用法:

 Type type = typeof(StudentViewModel); 
     PropertyInfo[] properties = type.GetProperties(); 
     var infos = properties.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(IsViewable))).ToList(); 
     List<StudentViewModel> models = result.Item1; 
     List<dynamic> list = models.Select(x => GetValue(x, infos)).ToList(); 
     string serializeObject = JsonConvert.SerializeObject(list); 
     var deserializeObject = JsonConvert.DeserializeObject<List<dynamic>>(serializeObject); 
     dataGridView1.DataSource = deserializeObject; 

enter image description here

enter image description here