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();
또는 다른 방법이나 더 좋은 방법이 있습니까?
나는 그게 내가 가장 단순한 방법으로하려는 것을 보여주기위한 것입니다. 여기 WrapPanel 일 필요가 없습니다. 그리드, 캔버스,리스트, 트리 또는 기타 컨테이너 일 수 있습니다. –