2016-12-06 30 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