teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

ボタンの青くなる処理削除、画像とグレーアウトがずれる原因を多分修正

2017/04/18 04:38

投稿

doubutweet
doubutweet

スコア141

answer CHANGED
@@ -1,4 +1,4 @@
1
- こんな感じでか?
1
+ こんな感じでしょうか?
2
2
  ```
3
3
  <Window x:Class="WpfApplication2.MainWindow"
4
4
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
@@ -8,8 +8,75 @@
8
8
  xmlns:local="clr-namespace:WpfApplication2"
9
9
  mc:Ignorable="d"
10
10
  Title="MainWindow" Height="350" Width="525">
11
+ <Window.Resources>
12
+ <!-- ボタンに表示する画像 -->
13
+ <BitmapImage x:Key="Image_Button_ON" UriSource="./Resources/user.png" />
14
+
15
+ <!-- ボタンのクリックをトリガーとしてグレーアウト用のボーダーの色を変更する -->
16
+ <Style x:Key="ClickButton" TargetType="Border">
17
+ <Style.Triggers>
18
+ <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=IsPressed}" Value="True" >
19
+ <Setter Property="Background" Value="Black" />
20
+ <Setter Property="Opacity" Value="0.5" />
21
+ </DataTrigger>
22
+ </Style.Triggers>
23
+ </Style>
24
+ </Window.Resources>
25
+
26
+ <Grid>
27
+ <Button>
28
+ <Button.Style>
29
+ <Style TargetType="Button">
30
+ <Setter Property="Template">
31
+ <Setter.Value>
32
+ <ControlTemplate TargetType="{x:Type Button}">
33
+ <!-- ボタンのデフォルトテンプレートの背景、ボーダーにする -->
34
+ <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
11
35
 
36
+ <!-- ボタンの子要素のコンテナ -->
37
+ <!-- HorizontalAlignmentとVerticalAlignmentをCenterにすることで画像とグレーアウトのサイズを統一し間延びするのを防ぐ -->
38
+ <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
39
+ <!-- 画像 -->
40
+ <Image Source="{StaticResource Image_Button_ON}" />
12
41
 
42
+ <!-- グレーアウト用 -->
43
+ <Border Style="{StaticResource ClickButton}" >
44
+ <!-- OpacityMaskで画像領域のみ色を変更する -->
45
+ <Border.OpacityMask>
46
+ <ImageBrush ImageSource="{StaticResource Image_Button_ON}" />
47
+ </Border.OpacityMask>
48
+ </Border>
49
+ </Grid>
50
+ </Border>
51
+ </ControlTemplate>
52
+ </Setter.Value>
53
+ </Setter>
54
+ </Style>
55
+ </Button.Style>
56
+ </Button>
57
+ </Grid>
58
+ </Window>
59
+ ```
60
+  
61
+  
62
+  
63
+ ## ボタンから青くなる処理を削除する参考
64
+ http://stackoverflow.com/questions/17259280/how-do-you-change-background-for-a-button-mouseover-in-wpf
65
+  
66
+  
67
+  
68
+ ## ここから下は以前の回答となります
69
+ ```
70
+ <Window x:Class="WpfApplication2.MainWindow"
71
+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
72
+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
73
+ xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
74
+ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
75
+ xmlns:local="clr-namespace:WpfApplication2"
76
+ mc:Ignorable="d"
77
+ Title="MainWindow" Height="350" Width="525">
78
+
79
+
13
80
  <Window.Resources>
14
81
  <!-- ボタンに表示する画像 -->
15
82
  <BitmapImage x:Key="ImageSource1" UriSource="./Resources/user.png" />