我正在尝试使用按钮控件中的图像,该图像通过显示不同的图像来对“悬停”和“按下”状态进行动画处理。因此,我为按钮控件定义了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); }
我在Button的Style属性设置器中设置了这些属性,如下所示
<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>
如您所见,我正在尝试从“按钮”的“控制模板”中访问自定义附加属性。我可以得到它通过硬编码工作来源的属性图像控制,但我wan't使用TemplateBinding代替
使用附加属性作为绑定源时,需要在属性路径中使用括号。您必须使用常规绑定而不是TemplateBinding:
<Image Source="{Binding Path=(gs:ButtonExtensions.ImagePressedSource),
RelativeSource={RelativeSource TemplatedParent}}"/>
还请注意,当ButtonExtensions类仅声明附加属性时,不必从DependencyObject派生。
还建议将DependencyProperty字段声明为只读:
public static readonly DependencyProperty ImagePressedSourceProperty = ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句