Button
から派生して、例えばに結合するいくつかの画像のプロパティを定義することができBackgroundImage
、MouseOverImage
など
Button
から派生する代わりに、画像を設定して、あなたのスタイルのものにバインドするattached propertiesを使用することであろうが、これらの添付プロパティにもなりません。これは、どこかで定義されなければならないだろうそれはより簡単です。
public class ImageButton : Button
{
public static readonly DependencyProperty NormalBackgroundImageProperty = DependencyProperty.Register(
"NormalBackgroundImage", typeof(ImageSource), typeof(ImageButton));
public static readonly DependencyProperty MouseOverBackgroundImageProperty = DependencyProperty.Register(
"MouseOverBackgroundImage", typeof(ImageSource), typeof(ImageButton));
public static readonly DependencyProperty PressedBackgroundImageProperty = DependencyProperty.Register(
"PressedBackgroundImage", typeof(ImageSource), typeof(ImageButton));
public ImageSource NormalBackgroundImage
{
get { return (ImageSource)GetValue(NormalBackgroundImageProperty); }
set { SetValue(NormalBackgroundImageProperty, value); }
}
public ImageSource MouseOverBackgroundImage
{
get { return (ImageSource)GetValue(MouseOverBackgroundImageProperty); }
set { SetValue(MouseOverBackgroundImageProperty, value); }
}
public ImageSource PressedBackgroundImage
{
get { return (ImageSource)GetValue(PressedBackgroundImageProperty); }
set { SetValue(PressedBackgroundImageProperty, value); }
}
}
と、以下の適切なスタイル:
は、ここで最初のソリューションの例です。このスタイルでは、ボタンのコンテンツにはContentPresenterもあり、TemplateBindingsの代わりにRelativeSource={RelativeSource TemplatedParent}
という正規のバインディングを使用することに注意してください。これらは実行時に評価されます。
<Style TargetType="local:ImageButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:ImageButton">
<Grid Margin="{TemplateBinding Margin}">
<Image x:Name="img" Source="{Binding NormalBackgroundImage, RelativeSource={RelativeSource TemplatedParent}}" Stretch="None"/>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter TargetName="img" Property="Source" Value="{Binding MouseOverBackgroundImage, RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="img" Property="Source" Value="{Binding PressedBackgroundImage, RelativeSource={RelativeSource TemplatedParent}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
あなたはクラスImageButton
を含む名前空間/アセンブリへのマッピングとXAML名前空間local
を定義したり、交換する必要があります。
ボタンは、このように使用することができます
<local:ImageButton
Margin="10"
NormalBackgroundImage="C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"
PressedBackgroundImage="C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg"
MouseOverBackgroundImage="C:\Users\Public\Pictures\Sample Pictures\Penguins.jpg"
Content="Click Me"/>
uは最初の提案の例を投稿してくださいできますか? – gilad
を明確にする - 私のコントロールには3つのプロパティがあります:通常のbgイメージ、ホバリングbgイメージ、bgイメージを押したテンプレートのように、私はそれらをバインドします。 – gilad
もちろん、後で。私は今会議に行かなければならないでしょう:-) 2時間ほどです。じゃあまたね。 – Clemens