2011-05-13 2 views
1

Grid 내에있는 WrapPanel에 동적으로 단추를 추가하려고하지만 WrapPanel 참조 (_innerPanel 속성)는 OnApplyTemplate이 호출 될 때까지 유효하지 않습니다.강제로 OnApplyTemplate을 실행합니다.

<s:MyGrid> 
    <WrapPanel x:Name="PART_InnerPanel"> 

    </WrapPanel> 
</s:MyGrid> 

에는 myGrid 클래스 : XAML 오른쪽에 정의 된 것을

MyGrid g = new MyGrid(); 
g.ApplyTemplate(); // <-- doesn't do anything 
g.UpdateLayout(); // <-- doesn't do anything 
if(g.Panel != null) // <-- it's NULL here as OnApplyTemplate hasn't get called 
{ 
    g.Panel.Children.Add(new Button()); 
} 

가 어떻게 WrapPanel의 참조를 얻을 : 코드 내부

public class MyGrid: Grid 
{ 
    WrapPanel _innerPanel; 

    public WrapPanel Panel 
    { 
     get{return _innerPanel;} 
    } 

    static MyGrid() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyGrid), new FrameworkPropertyMetadata(typeof(MyGrid))); 
    } 

    public override void OnApplyTemplate() 
    { 
     base.OnApplyTemplate(); 
     _innerPanel = Template.FindName("PART_InnerPanel", this) as WrapPanel; 
     if (_innerPanel == null) 
      throw new ResourceReferenceKeyNotFoundException("Invalid template"); 
    } 
} 

여기

는 XMAL입니다 라인 이후

MyGrid g = new MyGrid(); 

또는 다른 방법이나 더 좋은 방법이 있습니까?

답변

0

내가 사용하는 솔루션은 (당신처럼) OnApplyTemplate 재정의에 _innerPanel을 설정하고 사용하려고 할 때 항상 null인지 확인하는 것입니다.

템플릿 디자이너가 컨트롤을 추가한다고 보장 할 수 없기 때문에 필드를 외부로 노출하지 않습니다. 당신이하는 것처럼 확인을하면 보장이 있지만 여전히 WPF 엔진을 사용하여 템플릿을로드해야합니다.

컨트롤이 트리에 추가되고 템플릿을 찾을 수 있도록 만들어진 컨트롤이 만들어진 후에야 있습니다.

그래서 나는 당신이 요구하는 것을 가질 수 없다고 생각합니다.

0

자녀를 컨트롤에 추가하려면 ItemsControl에서 컨트롤을 파생해야합니다. Panel을 드러내는 대신 ItemsControl의 Items 속성 안에 항목을 추가하는 것이 좋지 않으며 ItemsControl은 모양과 느낌을 사용자 정의하는 여러 가지 방법을 제공합니다.

+0

나는 그게 내가 가장 단순한 방법으로하려는 것을 보여주기위한 것입니다. 여기 WrapPanel 일 필요가 없습니다. 그리드, 캔버스,리스트, 트리 또는 기타 컨테이너 일 수 있습니다. –

관련 문제