1. 程式人生 > >WPF中通過代碼定義模板

WPF中通過代碼定義模板

source image back actor width .so bsp app ima

原文:WPF中通過代碼定義模板

WPF中可以再XAML中定義模板,也可以通過C#代碼定義模板,通過代碼可能更清楚的看清其邏輯,而且代碼的好處就是可以隨時動態的去操作,而在XAML中定義的一般都是靜態的。 


//控件呈現的顯示內容1(這裏為Image) FrameworkElementFactory fe = new FrameworkElementFactory(typeof(Image), "Image"); BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.UriSource
= new Uri(@"E://MainBackground.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;

WPF中通過代碼定義模板