我爱电脑技术论坛's Archiver

白雪公主 发表于 2008-3-30 09:21

关于C#代码实现ControlTemplate

现在主流的控件模板和样式是引用XAML资源,不过感觉没有c#代码实现那么灵活,现介绍一下代码实现 ControlTemplate的方法:
0A"iY+~K
BeKZp rh#S"Q4A7f 以下是引用片段: Iix:GH5a@
          //控件呈现的显示内容1(这里为Image)
8dV4H4E!lC            FrameworkElementFactory fe = new FrameworkElementFactory(typeof(Image), "Image");
0k)S:G ["]2^ ?5ziO(S
C ZbP Mm             BitmapImage bi = new BitmapImage();
&O*i;L n$P a7`4b             bi.BeginInit(); &V5|3L)Q*_ ATe
            bi.UriSource = new Uri(@"E:ChartControlHanYangChartControlImageMainBackground.jpg");
R@S kmf%e&@             bi.EndInit(); r3`$}6YcOm!DL
)V;Q\ W`!N ~
            fe.SetValue(Image.SourceProperty, bi); W5R7WD&B H5j

Sh;~.V+H1n!F.F`             //控件呈现的显示内容2(这里为TextBox) b Rf T(s
            FrameworkElementFactory fe2 = new FrameworkElementFactory(typeof(TextBox), "TextBox");
}8p%sO{}$~3~             fe2.SetValue(TextBox.WidthProperty,100.0); "y1@+V+K@PM `}4O+lZ
            fe2.SetValue(TextBox.HeightProperty, 100.0);
A/LL8Y{ jff'v`RN
            //把要呈现的显示内容封装起来 (k(P_7@$d%CL%~
            FrameworkElementFactory f = new FrameworkElementFactory(typeof(Grid), "Grid");
vU%M~6IP             f.AppendChild(fe);
Q ns%H J f1jq.S             f.AppendChild(fe2); (dm^B1Py&{ B
I:ph3E[_
           //控件模板 "Z1Xhg]a"q^y
           ControlTemplate ct = new ControlTemplate(typeof(Button)); u!~I,P|{
           ct.VisualTree = f;
M flP5[$^!Dm 2u!kN#`-e"X4k
            //修改Button 的Template  Ko8o,T D~ xa0g
            Button btn = new Button(); ,Z#H0ClL"q1n&JV
            btn.Template = ct;

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.