I said one of XAML advantages is in its short code for
generating a UI. You can use programming languages to build your user
interface but should avoid it when you can use XAML markup. Listing 7 is the
code equivalent for Listing 1 and Listing 2. Obviously, you like to use XAML instead
of this approach, but sometimes it is necessary to do this via code. You can
use any .NET language to start coding for Windows Presentation Foundation.
Listing 7
private TextBox MyTextBox = new TextBox();
private Button btnClick = new Button();
private StackPanel stackPanel = new StackPanel();
public Window1()
{
// Create TextBox
this.MyTextBox.Width = 200;
this.MyTextBox.Height = 30;
this.MyTextBox.Margin = new Thickness(40);
this.MyTextBox.Name = "MyTextBox";
// Create Button
btnClick.Width = 60;
btnClick.Height = 20;
btnClick.Content = "Click me!";
btnClick.Click +=
new RoutedEventHandler(ButtonClickHandler);
// Layout Controls
this.stackPanel.Children.Add(MyTextBox);
this.stackPanel.Children.Add(btnClick);
this.Content = stackPanel;
}
void ButtonClickHandler(object sender, RoutedEventArgs e)
{
MessageBox.Show(string.Format
("You typed '{0}' in TextBox!", this.MyTextBox.Text), "XAML");
}
Note that this code does not generate a Window itself!