通过模板绑定更改路径属性

时间:2011-05-20 06:48:38

标签: wpf templates data-binding controltemplate templatebinding

我有一个包含路径的控件模板(除了其他控件)。调整控件大小时应调整路径大小。描述路径的点和大小可以表示为对照大小的相对分数。

以下是模板的摘录:

<Path Stroke="Gray" StrokeThickness="5">
    <Path.Data>
        <PathGeometry>
            <PathFigure StartPoint="{TemplateBinding Start}" >
                <ArcSegment Point="{TemplateBinding End}" Size="{TemplateBinding Size}" RotationAngle="0" IsLargeArc="True" />
            </PathFigure>
        </PathGeometry>
    </Path.Data>
</Path>

Start和End是Point类型的DependencyProperties,Size是Type Size的DependencyProperty。

我目前正在做的是收听FrameworkElement.SizeChanged事件:

void OperationModeIndicator_SizeChanged( object sender, SizeChangedEventArgs e )
{
    this.Size = new Size( e.NewSize.Width * 0.45f, e.NewSize.Height * 0.45f );
    this.Start = new Point( e.NewSize.Width * 0.35f, e.NewSize.Height * 0.1f );
    this.End = new Point( e.NewSize.Width * 0.65f, e.NewSize.Height * 0.1f );
}

现在的问题是: 是否有另一种(更优雅的)方法将路径的属性绑定到父控件的大小?

1 个答案:

答案 0 :(得分:1)

你所拥有的可能是实现这一目标的最佳方式。

另一种方法是构建一个公开两个公共属性的自定义IMultiValueConverter:WidthPercentage和HeightPercentage。然后,您可以绑定到模板化父级的ActualWidth / ActualHeight。

public class MyConverter : IMultiValueConverter {

    public double HeightPercentage { get; set; }
    public double WidthPercentage { get; set; }

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
        // TODO: Validate values size and types

        return new Point(((double)values[0]) * this.WidthPercentage, ((double)values[1]) * this.HeightPercentage);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
        // No-op or throw
    }

}

您使用的是:

<local:MyConverter x:Key="StartPointConverter"
    WidthPercentage="0.35" HeightPercentage="0.1" />

<!-- ... -->

<PathFigure>
    <PathFigure.StartPoint>
        <MultiBinding Converter="{StaticResource StartPointConverter}">
            <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="ActualWidth" />
            <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="ActualHeight" />
        </MultiBinding>
    </PathFigure.StartPoint>
    <!-- ... -->
</PathFigure>