2017-01-30 1 views
0

예를 들어 버튼을 프로그래밍 방식으로 추가하려는 스택 패널이 있다고 가정 해보십시오.컨트롤을 한 번 만들고 필요할 때마다 생성 할 수 있습니까?

StackPanel의에 버튼을 생성 및 추가에 대한 뒤에 코드는 다음과 같습니다

Button button = new Button(); 
button.Content = "Button"; 
button.HorizontalAlignment = HorizontalAlignment.Left; 
button.Name = "Button" + i 
stackPanel1.Children.Add(button); 

내 질문은 - 그것이 가능 버튼을 한 번 생성에 추가 할 수있는 템플릿의 일종으로 그것을 가지고 생성 코드를 다시 거치지 않고 필요할 때마다 스택 패널?

답변

0

WPF에서 각 UIElement는 주어진 시간에 한 컨트롤의 논리적 하위가 될 수 있습니다. WPF Error: Specified element is already the logical child of another element. Disconnect it first을 참조하십시오. 따라서 동일한 버튼을 사용하여 나중에 다른 컨트롤에 추가 할 수는 없습니다. 그 장판을 치웠어

하지만 재활용 할 수 있습니다. Optimizing Performance: Controls을 참조하십시오. 특히 MeasureOverrideArrangeOverride stackpanel을 덮어 쓰는 경우

많은 컨트롤이 포함 된 그리드가 있기 때문에 실제로 리사이클을 작성했습니다. 일종의 가상화 그리드를 구현하고 싶었습니다. 다음은 수업의 주요 방법입니다.

internal class Recycler 
{ 
    private UIElementCollection _children; 

    public Recycler(UIElementCollection children) 
    { 
     _children = children; 
     //You need this because you're not going to remove any 
     //UIElement from your control without calling this class 
    } 

    public void Recycle(UIElement uie) 
    { 
     //Keep this element for recycling, remove it from Children 
    } 

    public UIElement GiveMeAnElement(Type type) 
    { 
     //Return one of the elements you kept of this type, or 
     //if none remain create one using the default constructor 
    } 
} 
관련 문제