天天看點

WPF中通過代碼定義模闆

原文: 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;