カスタム スタイルを使用している WPF アプリケーションがあります。その中には、それぞれカスタムの背景画像を持つ一連のボタンがあります。ボタンごとに、通常の画像とマウスダウン画像を提供しています。単一のスタイルでこれを行う簡単な方法はありますか (そして、ケースバイケースで各ボタンをカスタマイズします)?
現在、ボタンごとに新しいスタイルを作成していますが、これが最善の方法ではないでしょうか?
XAML のみのソリューションの場合、これを考慮することができます:-
次のようなスタイルの一部としてコントロール テンプレートを使用していると仮定しています。
<Style x:Key="MyButtonStyle" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Image x:Name="img" Style="{DynamicResource NormalImage}"/>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Source" TargetName="img" Value="Images\DisabledImage.png"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
私はここでコントロール テンプレートをバラバラにしましたが、あなたのものはより洗練されているかもしれません
上記のスタイルと同じ領域に次のスタイルを追加すると、デフォルトのケースに使用する画像が指定されます
<Style x:Key="NormalImage" TargetType="{x:Type Image}">
<Setter Property="Source" Value="Images/DeafultImage.png"/>
</Style>
ボタンを使用する必要がある場合は、XAML をさらに下に移動すると、次のように実行できます。
<Button Style="{DynamicResource MyButtonStyle}" >
<Button.Resources>
<Style x:Key="NormalImage" TargetType="{x:Type Image}">
<Setter Property="Source" Value="Images/OverrideImage.png"/>
</Style>
</Button.Resources>
</Button>
見栄えはよくありませんが、それでもマスター スタイルを使用でき、複数のスタイルを使用するよりもわずかに短く、重複が少なくなります。
これが機能する方法は、リソース名「NormalImage」が最初にボタンのリソース (通常は空) で検索され、次に親コンテナー、ページ/ウィンドウ リソース、さらにはアプリケーション リソースに至るまで検索されます。最初の一致が勝つため、この場合、OverrideImage.png を参照する「NormalImage」と呼ばれるローカルで定義されたスタイルが、DefaultImage.png を参照する同じ名前を持つウィンドウ/ページ/コンテナー レベルのリソースより先に選択されます。
すべてのボタンまたはほとんどのボタンがこのスタイルを使用する場合は、スタイル定義から x:Key="MyButtonStyle" を削除します。そうすれば、スタイルを明示的に指定しなくても、WPF はスコープ内のすべてのボタンでスタイルを使用します。その後、style="{x:null}" を使用して、デフォルト スタイルを明示的に使用しないようにすることができます。したがって:-
<Window.Resources>
<Style x:Key="NormalImage" TargetType="{x:Type Image}">
<Setter Property="Source" Value="Images/DeafultImage.png"/>
</Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
...
</Setter>
</Style>
</Window.Resources>
<Button >
<Button.Resources>
<Style x:Key="NormalImage" TargetType="{x:Type Image}">
<Setter Property="Source" Value="Images/OverrideImage.png"/>
</Style>
</Button.Resources>
</Button>
<Button Style="{x:null}>Normal Button</Button>
You can create the style in a ResourceDictionary then merge that dictionary into your controls resources. If you give the style a key then you can bind any button to that style.
For example:
<Style x:Key="imageButton" ControlType="{x:Type Button}">
...
</Style>
<Button Style="{DynamicResource imageButton}" />