今回は
ToggleButton(System.Windows.Controls.Primitives)です。
ToggleButtonは「System.Windows.Controls.Primitives名前空間」に属するコントロールなので標準コントロールではありませんが、
前回Buttonクラスを取り上げたので続けてButton系のコントロールを取り上げようと思います。
まずはMSDNの説明を見てみましょう。
CheckBox などの、状態を切り替えることができるコントロールの基本クラス
ちょっと説明が足りなすぎる感じがしますがそれはさておき、ToggleButtonクラスは「2つ又は、3つ」の状態を持ったボタンです。
まずはその状態を見てみましょう。
- 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>
<ToggleButton IsChecked="False">Unchecked</ToggleButton>
<ToggleButton IsChecked="True">Checked</ToggleButton>
<ToggleButton IsThreeState="True" IsChecked="{x:Null}">Null</ToggleButton>
</StackPanel>
</Window>
上記例では「
True・False・Null」の3つの状態を持ったToggleButtonを作成しています。
2つ、3つの状態の切り替えは
IsThreeStateプロパティを使用する事で変更する事が可能です。
画像からも解るとおり、True・Falseの状態によってボタンの背景色も変化します。Trueの場合はずっとクリックしたままのようにへこんだ状態になり、Falseの場合は元に戻る状態になります。
さて、説明の「CheckBoxなどの、状態を切り替える事ができる」とありますが、これはCheckBoxコントロールなどにもIsThreeStateプロパティがある為です。
その例を見てみましょう。
- 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">
<Window.Resources>
<Style TargetType="{x:Type ToggleButton}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="False">
<Setter Property="Content" Value="Unchecked" />
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Content" Value="Checked" />
</Trigger>
<Trigger Property="IsChecked" Value="{x:Null}">
<Setter Property="Content" Value="Null" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Orientation="Horizontal" Margin="10" >
<CheckBox IsChecked="{Binding ElementName=Sample_ToggleButton, Path=IsChecked}" VerticalAlignment="Center" Margin="5"/>
<ToggleButton Name="Sample_ToggleButton" IsThreeState="True" IsChecked="{x:Null}" Width="100"/>
</StackPanel>
</Window>
上記例ではCheckBoxコントロールのIsCheckedプロパティとToggleButtonコントロールのIsCheckedプロパティをバインドさせている例です。
このように実装する事で、CheckBoxなどの状態を切り替える事が出来るようになります。
ToggleButtonコントロールは、ComboBoxコントロールやExpanderコントロールなどの「▼」の部分などに使用されています。
クリックする事による状態の切り替えの特性が、ComboBoxのドロップダウンの展開や、Expanderコントロールのデータの展開に良く合う事がご理解頂けるかと思います。
ToggleButtonコントロール単体での使用はあまり見かけませんが、独自のカスタムコントロールなどで展開可能なコントロールを作成する場合などには良いのではないでしょうか。
今回は「ToggleButtonコントロール」でした。
to be continue・・・