2008-08-27 2 views
4

사용자가 선택한 열에 따라 동적으로 데이터 뷰에 추가되는 ASP.Net 데이터 뷰 열 템플릿이 두 개 있습니다.동적으로 추가 된 Web.UI.ITemplate 클래스의 모범 사례

이 템플릿 세포는 사용자 정의 데이터 바인딩을 처리해야합니다

public class CustomColumnTemplate: 
    ITemplate 
{ 
    public void InstantiateIn(Control container) 
    { 
     //create a new label 
     Label contentLabel = new Label(); 

     //add a custom data binding 
     contentLabel.DataBinding += 
      (sender, e) => 
      { 
       //do custom stuff at databind time 
       contentLabel.Text = //bound content 
      }; 

     //add the label to the cell 
     container.Controls.Add(contentLabel); 
    } 
} 

... 

myGridView.Columns.Add(new TemplateField 
    { 
     ItemTemplate = new CustomColumnTemplate(), 
     HeaderText = "Custom column" 
    }); 

는 첫째로이 오히려 지저분 해 보이지만, 자원 문제도있다. Label이 생성되어 InstantiateIn에 처리 할 수 ​​없습니다. 그 이유는 데이터 바인드가 없기 때문입니다.

이러한 컨트롤에는 더 좋은 패턴이 있습니까?

데이터 바인딩 후 레이블이 처리되고 렌더링되는지 확인하는 방법이 있습니까?

답변

2

저는 템플릿 컨트롤로 광범위하게 작업했으며 더 나은 솔루션을 찾지 못했습니다.

왜 이벤트 처리기에서 contentLable을 참조하고 있습니까?

보낸 사람은 레이블에 캐스팅하고 레이블을 참조 할 수있는 레이블입니다. 아래처럼.

 //add a custom data binding 
     contentLabel.DataBinding += 
      (object sender, EventArgs e) => 
      { 
       //do custom stuff at databind time 
       ((Label)sender).Text = //bound content 
      }; 

그런 다음 InstantiateIn에서 레이블 참조를 처리 할 수 ​​있어야합니다.

참고 테스트하지 않았습니다.

1

템플릿을 IDisposable으로 구현 한 다음 템플릿의 Dispose 메서드로 컨트롤을 처리하십시오. 물론 이것은 당신이 만든 컨트롤을 추적하기 위해 어떤 종류의 컬렉션이 필요하다는 것을 의미합니다.

public class CustomColumnTemplate : 
    ITemplate, IDisposable 
{ 
    private readonly ICollection<Control> labels = new List<Control>(); 

    public void Dispose() 
    { 
     foreach (Control label in this.labels) 
      label.Dispose(); 
    } 

    public void InstantiateIn(Control container) 
    { 
     //create a new label 
     Label contentLabel = new Label(); 

     this.labels.Add(contentLabel); 

...

 //add the label to the cell 
     container.Controls.Add(contentLabel); 
    } 
} 

는 이제 여전히 템플릿을 배치하는 문제에 직면 : 여기에 대해 이동하는 방법 중 하나입니다. 템플릿에 Dispose을 호출하면 모든 라벨이 삭제되므로 템플릿은 책임있는 메모리 소비자가됩니다.

UPDATE

This link on MSDN은 컨트롤이 페이지의 컨트롤 트리에 뿌리를 자동으로 프레임 워크에 의해 배치되기 때문에 템플릿이 IDisposable을 구현하기 위해 아마도 그것은 필요가 없습니다 것을 제안!