10

私の WPF ウィンドウ アプリケーションでは、ボタンの上にマウスを置くと、ボタンの背景画像が消え、ボタンに画像がないように見えます。私が欲しいのは、マウスがボタンの上にあるとき、またはボタンがクリックされたときに、画像がボタンに表示され、消えてはならないということです。

これが私のコードです:

 <Button Margin="465, 3, 0, 0" Width="25" Height="20" IsEnabled="True" IsDefault="False" IsCancel="False" BorderBrush="{x:Null}" ToolTip="Reload pads list"> <Button.Background> <ImageBrush ImageSource="/FieldPlanner;component/Images/reload.gif" /> </Button.Background> </Button>
4

2 に答える 2

10

あなたに起こっていることは正常です。ボタンを作成すると、変更/上書きしない場合に備えて、デフォルトのプロパティが使用されます。

この場合、ボタンを作成するときにBackgroundプロパティをオーバーライドしますが、それはボタンの通常の状態に対してのみです。ホバリング時にも背景を変更したい場合は、ボタンにそうするように指示する必要があります。

この目的のために、次のように、スタイルを使用してボタン Templateをオーバーライドすることをお勧めします。

<Window x:Class="ButtonTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <ImageBrush x:Key="ButtonImage" ImageSource="/ButtonTest;component/Resources/ok.png"></ImageBrush>
    <Style TargetType="Button">
        <Setter Property="Background" Value="{StaticResource ButtonImage}"></Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                    Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                    SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" RecognizesAccessKey="True"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Blue" />
                            <Setter Property="Cursor" Value="Hand" />
                            <!-- If we don't tell the background to change on hover, it will remain the same -->
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="84,75,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>

この場合、このスタイルはすべてのボタンに適用されます。スタイルに を追加しx:Keyてスタイルを適用するボタンを指定し、それをボタンで指定できます。

<Style TargetType="Button" x:Key="ButtonStyled">

.....

<Button Style="{StaticResource ButtonStyled}" Content="Button" Height="23" HorizontalAlignment="Left" Margin="84,75,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
于 2013-06-18T10:30:55.910 に答える