WPF の楽しみはStyleから

WPF のグラフィカルな面白さ、そのはじめはスタイルですね。

もともと持っているボタンのプロパティをまとめて変更する定義セットですが、WPFコントロールは回転など今までのコントロールよりも自由度が高くなっているのでそれだけでも面白い要素は多いですね。

<Viewbox
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
>

 <StackPanel Orientation="Horizontal" Margin="20">

Style は普通このようにリソースとして定義します。上位のオブジェクトのリソースとして定義されたりしますが、アプリ全体なら Apllication.Resource となります。

  <StackPanel.Resources>
   <Style x:Key="buttonStyle">
    <Setter Property="Button.FontSize" Value="22"/>
    <Setter Property="Button.Background" Value="Purple"/>
    <Setter Property="Button.Foreground" Value="White"/>
    <Setter Property="Button.Height" Value="50"/>
    <Setter Property="Button.Width" Value="50"/>
    <Setter Property="Button.RenderTransformOrigin" Value=".5,.5"/>
    <Setter Property="Button.RenderTransform">
     <Setter.Value>
      <RotateTransform Angle="10"/>
     </Setter.Value>
    </Setter>
   </Style>
  </StackPanel.Resources>

Style はコントロール側から指定して使います。定義セットをいくつも作っておけばいろいろバリエーションが出来ます。MyButton Style をいくつも持っていると面白いかもしれませんね。

  <Button Style="{StaticResource buttonStyle}">1</Button>
  <Button Style="{StaticResource buttonStyle}">2</Button>
  <Button Style="{StaticResource buttonStyle}">3</Button>
 </StackPanel>
</Viewbox>

マウスを持っていくとこのように水色になりますが、これはVistaでWPFアプリケーションを実行したときの標準的な動きです。これ以上の定義をしようとするとだんだんStyleでは難しくなってきたりします。

image

まずはここから楽しみましょう。