gpt4 book ai didi

wpf - 自定义附加属性的模板绑定(bind)

转载 作者:行者123 更新时间:2023-12-04 13:45:29 25 4
gpt4 key购买 nike

我正在尝试在按钮控件中使用图像,它通过显示不同的图像在悬停和按下状态下进行动画处理。因此,我为按钮控件定义了 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 属性 setter 中设置了这些属性,如下所示
    <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>

如您所见,我正在尝试从按钮的控制模板中访问自定义附加属性。我可以通过硬编码 来让它工作。来源 的属性图片 控制,但我不想使用 模板绑定(bind) 反而

最佳答案

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

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

另请注意,当仅声明附加属性时,您的 ButtonExtensions 类不需要从 DependencyObject 派生。

还建议将 DependencyProperty 字段声明为只读:
public static readonly DependencyProperty ImagePressedSourceProperty = ...

关于wpf - 自定义附加属性的模板绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com