2010-03-28 4 views
4

단추의 템플릿을 프로그래밍 방식으로 설정하려면 어떻게해야합니까?WPF에서 ControlTemplate을 프로그래밍 방식으로 만듭니다.

Polygon buttonPolygon = new Polygon(); 
buttonPolygon.Points = buttonPointCollection; 
buttonPolygon.Stroke = Brushes.Yellow; 
buttonPolygon.StrokeThickness = 2; 

// create ControlTemplate based on polygon 
ControlTemplate template = new ControlTemplate(); 
template.Childeren.Add(buttonPolygon); // This does not work! What's the right way? 

//create button based on controltemplate 
Button button = new Button(); 
button.Template = template; 

그래서 버튼의 템플릿으로 Polygon을 설정하는 방법이 필요합니다. 제안?

감사합니다.

답변

4

공식적으로 새 ControlTemplate의 XAML을 문자열로 만든 다음 XamlReader.Parse를 사용하여 ControlTemplate 개체로 구체화해야합니다.

구조화 된 방법으로 FrameworkElementFactory 클래스를 사용하면 FrameworkElementFactory를 만들고 ControlTemplate.VisualTree를 해당 FEF로 설정합니다. 이렇게하면 유형 안전성이 향상되고 객체 트리를 쓰는 것만으로도 다시 읽을 수 있습니다. 그러나 공식적으로 사용되지 않으며 복잡한 템플릿이 있으면 다소 복잡해 질 수 있습니다.

두 접근법의 예는 How to setup a WPF datatemplate in code for a treeview?을 참조하십시오.이 접근법은 DataTemplate의 컨텍스트로 작성되었지만 ControlTemplate에서도 작동합니다.

+2

턱. 어쨌든 고마워. :-) –

관련 문제