首页 > 代码库 > 加载和编译Xaml(宝典2)

加载和编译Xaml(宝典2)

三个方式来实现wpf的应用程序

1/只使用代码

好处:就是随意的定制应用程序,相比之下xaml文档,它们只能作为固定的不变的资源嵌入到程序集中

坏处:因为wpf控件包含没有参数的构造函数,所以一个简单的控件就可写很多代码

demo:

新建一个普通类(不是窗口类)

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;

namespace WPF_Valuable
{
    class Window1:Window
    {
        private Button button1;
        public Window1()
        {
            InitializeComponent();
        }
        private void InitializeComponent()
        {
            //configure the form
            this.Width = this.Height = 285;
            this.Left = this.Top = 100;
            this.Title = "Code-only Window";

            //creater a container to hold a button
            DockPanel panel = new DockPanel();

            //Creater a button.
            button1 = new Button();
            button1.Content = "Please click me";
            button1.Margin = new System.Windows.Thickness(30);
            //Attach  the event handler
            button1.Click += button1_Click;

            IAddChild container = panel;
            container.AddChild(button1);

            container = this;
            container.AddChild(panel);

        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            button1.Content = "Thank you ";
        }
    }
}
View Code

技术分享

技术分享

 

加载和编译Xaml(宝典2)