#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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        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" />
    </StackPanel>
</Window>

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
     sp.Children.Add(b2);

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

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: