Page 43 加载和编译XAML

只用代码创建WPF应用:

1、VS2010新建|Visual C#|Windows窗体应用程序;名称(NonCompiledXaml)

2、Solution Explorer中删除Form1.cs组

3、新建项Visual C#|类;名称(Window1)

4、Window1.cs的代码

using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Drawing;
using System.Windows.Media;

public class Window1 : Window
{
    private Button button1;

    public Window1()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        this.Width = this.Height = 285;
        this.Left = this.Top = 100;
        this.Title = "Code-Only Window";

        DockPanel panel = new DockPanel();

        button1 = new Button();
        button1.Content = "Please click me";
        button1.Margin = new Thickness(30);
        LinearGradientBrush brush = new LinearGradientBrush();
        GradientStop gs1 = new GradientStop();
        gs1.Offset = 0.00;
        gs1.Color = Colors.AliceBlue;
        brush.GradientStops.Add(gs1);

        GradientStop gs2 = new GradientStop();
        gs2.Offset = 0.50;
        gs2.Color = Colors.CadetBlue;
        brush.GradientStops.Add(gs2);

        GradientStop gs3 = new GradientStop();
        gs3.Offset = 1.00;
        gs3.Color = Colors.Wheat;
        brush.GradientStops.Add(gs3);
        button1.Background = brush;        

        button1.Click += button1_Click;

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

        container = this;
        container.AddChild(panel);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        button1.Content = "Thank you";
    }
}

5、修改program.cs内容为

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace NonCompiledXaml
{
    public class Program : Application
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Program app = new Program();
            app.MainWindow = new Window1();
            app.MainWindow.ShowDialog();
        }
    }
}

7、项目所引用的程序集如下

 

 

 

posted @ 2011-09-30 15:16  jacky_j2ee  阅读(210)  评论(0)    收藏  举报