#57 – Markup vs. Code

A WPF or Silverlight user interface is generally specified declaratively, using markup (XAML).  The XAML specifies the controls to be created and what their attributes should be.  But these controls could also be created procedurally, in code (e.g. C#).

For example, consider the following XAML code that creates two buttons in a StackPanel:

<Window x:Class="WpfApplication.MainWindow"
        Title="MainWindow" Height="224" Width="334">
    <StackPanel Orientation="Horizontal">
        <Button Name="button1" Content="OK" Height="23" Width="75" />
        <Button Name="button2" Content="Cancel" Height="23" Width="75" />

Assuming that the Window object already exists, the above XAML would be equivalent to the following C# code:

 private void Window_Initialized(object sender, EventArgs e)
     StackPanel sp = new StackPanel();
     sp.Orientation = Orientation.Horizontal;

     Button b1 = new Button();
     b1.Name = "button1";
     b1.Content = "OK";
     b1.Height = 23;
     b1.Width = 75;

     Button b2 = new Button();
     b2.Name = "button2";
     b2.Content = "Cancel";
     b2.Height = 23;
     b2.Width = 75;

     sp.Children.Add(b1);   // Add buttons to StackPanel

     this.Content = sp;     // Add StackPanel to Window