2010-03-26 2 views
2

다음과 같은 경우에 DataGrid를 만든 다음 런타임에 내용을 채 웁니다.익명 형식 (런타임까지 속성을 알 수 없음)

내가 겪고있는 문제는 그리드를 만들 때까지 필드가 무엇인지 모르기 때문에 항목 소스를 올바르게 설정하는 방법을 모른다는 것입니다. 다음 코드에서 볼 수 있듯이 필드 이름을 열로 추가하면 항목을 반복하고이 시점에서 필드 이름이라고하는 속성을 설정하는 각 항목에 대해 익명 형식을 만들려고합니다. 예를 들어, 필드 이름 값

foreach (string fieldName in listViewFieldCollection) 
{ 
    DataGridTextColumn newColumn = new DataGridTextColumn 
             { 
              Header = fieldName, 
              Binding = new Binding(fieldName) 
             }; 

    dataGrid.Columns.Add(newColumn); 
} 

List<object> list = new List<object>(); 

foreach (ListItem listItem in listItems) 
{ 
    foreach (string fieldName in listViewFieldCollection) 
    { 
     list.Add(new 
        { 
         // I want to be able to dynamically build Anonymous type properties here 
         fieldName = listItem[fieldName] 
        }); 
    } 
} 

dataGrid.ItemsSource = list; 

. 나는 필드는 '제목'다음 '링크'라는 한 경우 내가 원하는에는 list.add (

list.Add(new 
       { 
        Title = listItem["Title"], 
        Link = listItem["Link"] 
       }); 

처럼 행동하지만 필드는 '관리자', '제목'과 '연봉'경우가해야 할 새로운

list.Add(new 
       { 
        Manager = listItem["Manager"], 
        Title = listItem["Title"], 
        Salary = listItem["Salary"], 
       }); 

답변

0

리플렉션을 사용할 수있는 것처럼 들립니다. 아래의 코드는 여러분을 시작할 수있는 무언가입니다. 스 니펫은 객체의 모든 속성을 반복합니다.

 foreach (var currentPropertyInformation in source.GetType().GetProperties()) 
     { 
      if ((currentPropertyInformation.GetGetMethod() == null) || (currentPropertyInformation.GetSetMethod() == null)) 
       continue; 

      if (string.Compare(currentPropertyInformation.Name, "Item") != 0) // handle non-enumerable properties 
      { 
       // place this snippet in method and yield info? 
      } 
      else // handle enumerable properties 
      { 
      } 
     } 
+0

환상적으로, 나는 가능한 한 빨리이 옵션을 제공 할 것입니다. 감사합니다 @ grlev –

1

그것은 반사 또는 codegeneration 없이는 불가능처럼 수행합니다.

new 
       { 
        Manager = listItem["Manager"], 
        Title = listItem["Title"], 
        Salary = listItem["Salary"], 
       } 

이러한 필드를 설정하는 세 개의 필드 다음 몇 줄의 클래스로 변환된다. 이것은. 컴파일러에 의해 codegenerated 루에서 이렇게됩니다 ntime 당신은 그것을 할 수 없다.