Is there a way to use WPF without XAML

You can write WPF apps w/o XAML. Everything you can achieve in xaml, you can achieve in C# code is really true but not the opposite.  But xaml is very handy to define styles and templates, or initialize tons of objects. It is much easier to read than c# code. And it is easy to maintain.

XAML is also mustly used in WPF UI bacause it makes it possible to have a dedicated designer (not programmer) to design the UI.

How to get this code going:

  • Create a Windows Presentation Foundation project named HelloWorldManual
  • Remove the App.xaml and Window1.xaml from the project
  • Add a new class file named MyWindow.cs and paste this into it:

using System;
using System.Windows;
using System.Windows.Controls;

namespace HelloWorldManual
{
    public class MyWindow : Window
    {
        private Label label1;

        public MyWindow()
        {
            Width = 300;
            Height = 300;

            Grid grid = new Grid();
            Content = grid;

            Button button1 = new Button();
            button1.Content = "Say Hello!";
            button1.Height = 23;
            button1.Margin = new Thickness(96, 50, 107, 0);
            button1.VerticalAlignment = System.Windows.VerticalAlignment.Top;
            button1.Click += new RoutedEventHandler(button1_Click);
            grid.Children.Add(button1);

            label1 = new Label();
            label1.Margin = new Thickness(84,115,74,119);
            grid.Children.Add(label1);


        }

        void button1_Click(object sender, RoutedEventArgs e)
        {
            label1.Content = "Hello WPF!";
        }

        [STAThread]
        public static void Main()
        {
            Application app = new Application();

            app.Run(new MyWindow());
        }
    }
}
By Sriramjithendra Posted in WPF, WPF

Leave a comment