現在主流的控件模板和樣式是引用XAML資源,不過感覺沒有c#代碼實現那麼靈活,現介紹一下代碼實現ControlTemplate的方法:
FrameworkElementFactoryfe=newFrameworkElementFactory(typeof(Image),"Image");
BitmapImagebi=newBitmapImage();
bi.BeginInit();
bi.UriSource=newUri(@"E:ChartControlHanYangChartControlImageMainBackground.jpg");
bi.EndInit();
fe.SetValue(Image.SourceProperty,bi);
//控件呈現的顯示內容2(這裏爲TextBox)
FrameworkElementFactoryfe2=newFrameworkElementFactory(typeof(TextBox),"TextBox");
fe2.SetValue(TextBox.WidthProperty,100.0);
fe2.SetValue(TextBox.HeightProperty,100.0);
//把要呈現的顯示內容封裝起來
FrameworkElementFactoryf=newFrameworkElementFactory(typeof(Grid),"Grid");
f.AppendChild(fe);
f.AppendChild(fe2);
//控件模板
ControlTemplatect=newControlTemplate(typeof(Button));
ct.VisualTree=f;
//修改Button的Template
Buttonbtn=newButton();
btn.Template=ct;