[WPF] WPF入門 ~コントロール [Button]~

投稿日 : 2009年3月30日 1:00
今回は標準コントロールのButton(System.Windows.Controls.Button)です。
Buttonコントロールも従来のWindows Formアプリケーションで良く使用されていたコントロールです。
まずはMSDNの説明を見てみましょう。

ButtonBase.Click イベントに反応する Windows ボタン コントロールを表します。

説明の通り、ボタンをクリックし何かしらの処理を行わす場合にButtonクラスは使用されます。
ではコントロールの使用例です。

- XAML -
<Window x:Class="Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" SizeToContent="WidthAndHeight">
    <StackPanel Orientation="Horizontal">
        <TextBox Name="Sample_TextBox" Width="120" Height="25" Margin="5" />
        <Button Click="Button_Click" Margin="5">Click!</Button>
    </StackPanel>
</Window>

- VB -
Class Window1
    Public Sub New()
 
        ' この呼び出しは、Windows フォーム デザイナで必要です。
        InitializeComponent()
 
        ' InitializeComponent() 呼び出しの後で初期化を追加します。
    End Sub
 
    Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        MessageBox.Show(Me.Sample_TextBox.Text & " が入力されています。")
    End Sub
End Class
- C# -
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }
 
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(this.Sample_TextBox.Text + " が入力されています。");
    }
}



上記例ではTextBoxに入力されている文字列を表示するだけの簡単な例ですが、このようにボタンを押下した時に何か実行処理を行わせたい場合などに良く使用されます。
WPFでは、Buttonコントロールはあるコントロールの要素の一部として(例えばToolBarコントロールなど)使用される事が多々あります。

ButtonコントロールはContentプロパティを持っているので、子要素を入れる事が出来ます。
子要素を入れレイアウトを簡単に変えることが出来ます。

- XAML -
<Window x:Class="Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" SizeToContent="WidthAndHeight">
    <StackPanel Orientation="Horizontal">
        <TextBox Name="Sample_TextBox" Width="120" Height="25" Margin="5" />
        <Button Click="Button_Click" Margin="5">
            <StackPanel Orientation="Horizontal">
                <TextBlock Margin="3">Click!</TextBlock>
                <Image Source="happyface.jpg" Width="20" Height="20"/>
            </StackPanel>
        </Button>
    </StackPanel>
</Window>



Buttonクラスは標準コントロールの中でも良く使用する事があるコントロールです。是非使えるようになりましょう。
また、今までのWindows Formアプリケーションで使用していたボタンは、ボタン自体のレイアウトの変更は基本的には行えませんでした。
WPFのボタンはとても簡単にレイアウトを変更したり、独自のボタンを作成する事が出来ます。それはまた別の機会に取り上げたいと思います。

今回は標準コントロールの「Buttonコントロール」でした。

to be continue・・・

フィードバック

# [WPF] WPF入門 ~コントロール [ToggleButton]~

2009/03/31 1:32 by .NETな日々
[WPF] WPF入門 ~コントロール [ToggleButton]~
コメントの入力
タイトル
名前
Url
コメント