WPF ControlTemplate and Binding
In the below code, MousePressImage
is a dependency property of class ButtonControl
.
The following Binding doesn't work. Appreciate your help in solving this issue.
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
开发者_如何学运维 Path=MousePressImage}"/>
<Style TargetType="{x:Type local:ButtonControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ButtonControl}">
<Border>
<Image x:Name="img"
Source="pack://application:,,,/Recipe_06_13;component/Resources/normal.bmp"
/>
</Border>
<!--<Border x:Name="border">
<Border.Background>
<ImageBrush x:Name="img"
ImageSource="/Recipe_06_13;component/Resources/fatal.png"/>
</Border.Background>
</Border>-->
<ControlTemplate.Triggers>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="img"
Property="Source"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=MousePressImage}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I create the ButtonControl
like this.
<local:ButtonControl Height="48" Width="160"
MouseOverImage="pack://application:,,,/Recipe_06_13;component/Resources/Over.bmp"
MousePressImage="pack://application:,,,/Recipe_06_13;component/Resources/Press.bmp"
DisableImage=" ">
</local:ButtonControl>
Because your trigger is on a ControlTemplate, you need to be getting the MousePressImage from the control instance being templated. To do this, use TemplateBinding
or (more reliably) RelativeSource TemplatedParent
:
<Setter TargetName="img"
Property="Source"
Value="{Binding RelativeSource={RelativeSource TemplatedParent},
Path=MousePressImage}" />
精彩评论