[WPF 筆記]設定 Button 背景圖

  • 2685
  • 0

摘要:[WPF 筆記]設定 Button 背景圖

1.設定圖片來源

    <ImageSource x:Key="YesPlay">Yes1.png</ImageSource>
    <ImageSource x:Key="YesStop">Yes2.png</ImageSource>

2.設定 Button 圖片,並在滑鼠移上時變更圖片的樣式

    <Style x:Key="MyButton" TargetType="{x:Type Button}">
        <Setter Property="Background">
            <Setter.Value>
                <ImageBrush ImageSource="{DynamicResource YesPlay}" Stretch="None"/>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}">
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
                                   Foreground="White" FontFamily="Microsoft JhengHei" FontSize="48">是</TextBlock>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background">
                    <Setter.Value>
                        <ImageBrush ImageSource="{DynamicResource YesStop}" Stretch="None" />
                    </Setter.Value>
                </Setter>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border Background="{TemplateBinding Background}">
                                <!--<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>-->
                                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" 
                                           Foreground="Black" FontFamily="Microsoft JhengHei" FontSize="48">是</TextBlock>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>

3. 引用設定樣式

        <Button Name="btn_PrintInvoice_Yes" Style="{DynamicResource MyButton}" ></Button>
 
4. 完成如下圖。
 
移上後如下圖。