我如何绑定到一个EllipseGeometry的Center属性



我试图在自定义控件内部移动椭圆,我关心它的中心点,所以我在Path内部使用EllipseGeometry,而不是单独使用Ellipse

所以我创建了这个自定义控件(CenterPoint硬编码为100,100):

Public Class RippleButton
  Inherits ButtonBase
    Shared Sub New()
    DefaultStyleKeyProperty.OverrideMetadata(GetType(RippleButton), New FrameworkPropertyMetadata(GetType(RippleButton)))
  End Sub
  Public Sub New()
    MyBase.New()
    CenterPoint = New Point(100, 100)
  End Sub

  Public Property CenterPoint As Point
    Get
      Return DirectCast(GetValue(CenterPointProperty), Point)
    End Get
    Set(ByVal value As Point)
      SetValue(CenterPointProperty, value)
    End Set
  End Property
  Public Shared ReadOnly CenterPointProperty As DependencyProperty = 
                         DependencyProperty.Register("CenterPoint", _
                         GetType(Point), GetType(RippleButton))
End Class

这个类的默认样式(EllipseGeometry的Center被绑定到控件的CenterPoint):

<Style TargetType="{x:Type local:RippleButton}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:RippleButton}">
        <Border Background="{TemplateBinding Background}"
                          BorderBrush="{TemplateBinding BorderBrush}"
                          BorderThickness="{TemplateBinding BorderThickness}">
          <Path Fill="Red" ClipToBounds="True">
            <Path.Data>
              <EllipseGeometry Center="{TemplateBinding CenterPoint}"
                               RadiusX="100"
                               RadiusY="100" />
            </Path.Data>
          </Path>
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

当我把RippleButton放在WPF窗口上时,红色椭圆总是在左上角,而不是100,100。这里发生了什么,我如何让它移动到在类中定义的中心点?

不知道为什么它不能与TemplateBinding一起工作,但您可以将其替换为常规绑定:

<EllipseGeometry
    Center="{Binding CenterPoint, RelativeSource={RelativeSource TemplatedParent}}"
    RadiusX="100" RadiusY="100" />

最新更新