我还是WPF的新手。我正在尝试创建一个按钮模板,该模板使用按钮形状的路径数据。我的应用程序有几个按钮,可执行类似的任务,但需要不同的形状。我正在尝试创建一个将路径数据传递给我的模板的附加属性。到目前为止我得到了什么:
附属物:
Public Class CustomShapeButton
Inherits Button
Public Shared PathDataProperty As DependencyProperty = DependencyProperty.RegisterAttached("PathData", GetType(Path), GetType(CustomShapeButton), New PropertyMetadata(Nothing))
Public Shared Sub SetPathData(obj As DependencyObject, value As Path)
obj.SetValue(PathDataProperty, value)
End Sub
Public Shared Function GetPathData(obj As DependencyObject) As Path
Return DirectCast(obj.GetValue(PathDataProperty), Path)
End Function
End Class
按钮模板,位于我的资源字典中:
<Style x:Key="TransparentNavButton" TargetType="{x:Type Button}">
<Setter Property="FontSize" Value="16"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Path x:Name="pth" Data="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=(hmi:CustomShapeButton.PathData)}" Stroke="Black" Stretch="Fill"/>
<ContentPresenter x:Name="ButtonContentPresenter" VerticalAlignment="Center" HorizontalAlignment="Right" Margin="0,0,4,0"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="pth" Property="Fill" Value="#60FF0000"/>
<Setter TargetName="pth" Property="Stroke" Value="Blue"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
然后尝试实现这样的事情:
<Button Content="Button" Width="60" Height="50" Style="{StaticResource TransparentNavButton}">
<hmi:CustomShapeButton.PathData>
<Path Data="M1 1 L20 0 L20 20 L0 20 Z"/>
</hmi:CustomShapeButton.PathData>
</Button>
我似乎无法在按钮上显示路径数据。我错过了什么?
答案 0 :(得分:2)
您的问题是,您正在创建Path
类型的附加属性,但会将其分配给模板中的PathData
属性,该属性的类型为Geometry
。要解决此问题,请更改附加的属性声明,如下所示:
Public Class CustomShapeButton
Public Shared PathDataProperty As DependencyProperty = DependencyProperty.RegisterAttached("PathData", GetType(Geometry), GetType(CustomShapeButton), New PropertyMetadata(Nothing))
Public Shared Sub SetPathData(obj As DependencyObject, value As Geometry)
obj.SetValue(PathDataProperty, value)
End Sub
Public Shared Function GetPathData(obj As DependencyObject) As Geometry
Return DirectCast(obj.GetValue(PathDataProperty), Geometry)
End Function
End Class
然后像这样使用它:
<Button Content="Button" Width="60" Height="50"
hmi:CustomShapeButton.PathData="M1 1 L20 0 L20 20 L0 20 Z"
Style="{StaticResource TransparentNavButton}" />
还有一点需要注意:您的CustomShapeButton
类不需要从Button
继承 - 事实上,它根本不需要继承任何东西。但是,如果您想创建自己的具有PathData
属性的派生按钮类,则可以从Button
继承,在这种情况下,您将PathData
声明为常规依赖属性而不是作为附属财产。