【问题标题】:How can I bind to the Center property of an EllipseGeometry?如何绑定到 EllipseGeometry 的 Center 属性?
【发布时间】:2014-07-02 22:58:13
【问题描述】:

我正在尝试在自定义控件内移动 Ellipse,并且我关心它的中心点,因此我在 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。这里发生了什么?如何让它移动到类中定义的 CenterPoint?

【问题讨论】:

    标签: wpf xaml wpf-controls


    【解决方案1】:

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

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

    【讨论】:

    • 好吧,我不知道有什么区别,但这有效。公认。希望有人能够解释为什么 TemplateBinding 在那里不起作用。
    • 请参阅this answer,了解 TemplateBinding 与使用 TemplatedParent 的常规绑定之间的区别。但是,这并不能解释为什么 TemplateBinding 在这里不起作用。
    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多