初めてのSilvelightアプリケーション「BMI計算」

Silverlightアプリケーションを作ってみます。題材は何でも良いのですが、巷では良くガジェット系のHallo WorldにBMI計算アプリケーションが取り上げられている気がするので、その流れに乗ってみます。
VisualStudioでSilverlightアプリケーションプロジェクトを新規作成します。名前をBMICalculatorにしました。
で、MainPage.xamlを下記のようにしました。

<UserControl x:Class="BMICalculator.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <StackPanel x:Name="LayoutRoot">
        <StackPanel Orientation="Horizontal" Margin="5">
            <TextBlock Text="体重" Width="80" VerticalAlignment="Center" Margin="5,0"/>
            <TextBox x:Name="TxbWeight" Width="150"/>
            <TextBlock Text="Kg" VerticalAlignment="Center" Margin="5,0"/>
        </StackPanel>
        <StackPanel Orientation="Horizontal" Margin="5">
            <TextBlock Text="身長" Width="80" VerticalAlignment="Center" Margin="5,0"/>
            <TextBox x:Name="TxbHeight" Width="150"/>
            <TextBlock Text="cm" VerticalAlignment="Center" Margin="5,0"/>
        </StackPanel>
        <Button x:Name="BtnCalc" Content="計算" Width="80" HorizontalAlignment="Left" Margin="20,0"/>
        <StackPanel Orientation="Horizontal" Margin="5">
            <TextBlock Text="あなたのBMI" Width="80" VerticalAlignment="Center" Margin="5,0"/>
            <TextBox x:Name="TbxBMI" Width="150" IsReadOnly="True"/>
        </StackPanel>
    </StackPanel>
</UserControl>

StackPanelに追加されたコントロールを子コントロールと呼びます。子コントロールは追加した順に縦に並んでいきます。
また、子コントロールを横に並べたいときは、

<StackPanel Orientation="Horizontal">

とします。
StackPanelを組み合わせると手軽にコントロールを並べられるので便利です。

また、MainPage.xaml.csには、計算ボタンのイベントハンドラBMIの計算ロジックを記述します。

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        this.RegistorEventHandler();
    }

    private void RegistorEventHandler()
    {
        BtnCalc.Click += new RoutedEventHandler(this.BtnCalc_Click);
    }

    private void BtnCalc_Click(object sender, RoutedEventArgs e)
    {
        // エラー結果表示テキストブロックを初期化
        TblValidateResult.Text = string.Empty;

        // 体重kg
        double weight;
        if (!double.TryParse(TbxWeight.Text, out weight) || weight <= 0)
        {
            TblValidateResult.Text = "体重は正の数字を入力してください";
            return;
        }

        // 身長m
        double height;
        if (!double.TryParse(TbxHeight.Text, out height) || height <= 0)
        {
            TblValidateResult.Text = "身長は正の数字を入力してください";
            return;
        }

        // BMI=体重(kg)/身長(m)の二乗 
        double bmi = weight / Math.Pow(height / 100D, 2);

        // bmiをコントロールにセットする。
        TbxBMI.Text = bmi.ToString();
    }
}

ちゃんとテキストボックス内の値を数値に変換できるかチェックしてからBMIの計算を行いましょう。