現在主流的控制項範本和樣式是引用XAML資源,不過感覺沒有c#代碼實現那麼靈活,現介紹一下代碼實現 ControlTemplate的方法:
//控制項呈現的顯示內容1(這裡為Image)
FrameworkElementFactory fe = new FrameworkElementFactory(typeof(Image), "Image");
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.UriSource = new Uri(@"E:ChartControlHanYangChartControlImageMainBackground.jpg");
bi.EndInit();
fe.SetValue(Image.SourceProperty, bi);
//控制項呈現的顯示內容2(這裡為TextBox)
FrameworkElementFactory fe2 = new FrameworkElementFactory(typeof(TextBox), "TextBox");
fe2.SetValue(TextBox.WidthProperty,100.0);
fe2.SetValue(TextBox.HeightProperty, 100.0);
//把要呈現的顯示內容封裝起來
FrameworkElementFactory f = new FrameworkElementFactory(typeof(Grid), "Grid");
f.AppendChild(fe);
f.AppendChild(fe2);
//控制項範本
ControlTemplate ct = new ControlTemplate(typeof(Button));
ct.VisualTree = f;
//修改Button 的Template
Button btn = new Button();
btn.Template = ct;