透過ボタンを作成する(XAML 版)

MSDN フォーラムのスレッドで、ボタンを透明にすると同時に枠も消したいとの話が出てたのでチャレンジしましたが、その後色々試した結果、こんな感じでいいんでないかと思いました。Button の Template の中身を Border のみにしています。フォーラムに書いたのより、遥かにシンプルになりました。

<Style TargetType="Button">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="Foreground" Value="Transparent"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Background="Transparent" />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


サンプルアプリの図。画面の中央が透明ボタンです。



適当なイメージを Window の背景に設定して試してみましょう。

XAML

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="280" Width="350" WindowStartupLocation="CenterScreen">
    <Window.Background>
        <ImageBrush ImageSource="/WpfApplication7;component/Images/1024x768_b.jpg" 
                    Stretch="UniformToFill" TileMode="None" />
    </Window.Background>
    <Window.Resources>
        <Style x:Key="TransparencyButton" TargetType="Button">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Foreground" Value="Transparent"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Background="Transparent" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Height="23" HorizontalAlignment="Left" 
                Margin="245,12,0,0" Name="button1" 
                VerticalAlignment="Top" Width="75" />
        <Button Height="80" HorizontalAlignment="Center" 
				Margin="0" Name="button2" Content="Test"
				VerticalAlignment="Center" Width="140" 
                Style="{StaticResource TransparencyButton}" />
    </Grid>
</Window>


実行するとこうなる・・・右上はただのボタン、画面中央に透明化したボタンを配置しています。全く見えません。
でもこれなら最初から Border 配置しとけばいいんでないかい?と突っ込まれそうな予感が(汗


XP の場合、Button にフォーカス当たると枠線のみ表示します。


Button の領域内をクリックすれば、当然イベントが発生します。

private void button1_Click(object sender, RoutedEventArgs e) {
    MessageBox.Show(sender.GetType().FullName);
}


ただし Windows7 の場合、フォーカスが当たっても枠線を表示しない。


OS のスタイルによって挙動が違うようですね。これはたぶん Vista も同様だと思う。様々な OS 上で仕様を統一しようと思うなら、やはり細かく作りこまなければならんようです。