自定义附加属性的模板绑定

5

我正在尝试在按钮控件中使用图像,并通过显示不同的图像来实现悬停和按下状态的动画效果。因此,我已经定义了如下所示的3个附加属性用于按钮控件。

public class ButtonExtensions : DependencyObject {
    public static DependencyProperty ImageSourceProperty = ...
    public static DependencyProperty ImageHoverSourceProperty = ...
    public static DependencyProperty ImagePressedSourceProperty =
        DependencyProperty.RegisterAttached("ImagePressedSource", typeof(string), typeof(ButtonExtensions));
    public static string GetImagePressedSource(Button target) { return (string)target.GetValue(ImagePressedSourceProperty); }
    public static void SetImagePressedSource(Button target, string value) { target.SetValue(ImagePressedSourceProperty, value); }

我在按钮的样式属性设置器中设置了以下属性:

    <Style x:Key="AddButtonStyle" TargetType="{x:Type Button}" >
        <Setter Property="gs:ButtonExtensions.ImageSource" Value="/HotelReservation.ControlLibrary;component/Images/add-record-icon.png"/>
        <Setter Property="gs:ButtonExtensions.ImageHoverSource" Value="/HotelReservation.ControlLibrary;component/Images/add-record-hover-icon.png"/>
        <Setter Property="gs:ButtonExtensions.ImagePressedSource" Value="/HotelReservation.ControlLibrary;component/Images/add-record-pressed-icon.png"/>

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid Height="32" Width="32">
                        <!-- How to use TemplateBinding Here. This does not work -->
                        <Image Name="Normal" Source="{TemplateBinding Property=gs:ButtonExtensions.ImageSource}" />
/>
                        <!-- This Works -->
                        <Image Name="Hover" Source="/HotelReservation.ControlLibrary;component/Images/add-record-hover-icon.png" Opacity="0"/>
                        <Image Name="Pressed" Source="/HotelReservation.ControlLibrary;component/Images/add-record-pressed-icon.png" Opacity="0" />
                    </Grid>
    ...

                </ControlTemplate>

            </Setter.Value>
        </Setter>
    </Style>

如您所见,我正在尝试在按钮的控件模板中访问自定义附加属性。我可以通过硬编码 Image 控件的 Source 属性来使其工作,但我想使用 TemplateBinding

1个回答

7

使用附加属性作为绑定源需要在属性路径中使用括号。您将不得不使用常规绑定而不是TemplateBinding:

<Image Source="{Binding Path=(gs:ButtonExtensions.ImagePressedSource),
                        RelativeSource={RelativeSource TemplatedParent}}"/>

请注意,当ButtonExtensions类仅声明附加属性时,它不需要派生自DependencyObject。
同时建议将DependencyProperty字段声明为只读。
public static readonly DependencyProperty ImagePressedSourceProperty = ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接