2011-05-20 59 views
1

我有一個包含路徑(除了其他控件)的控件模板。調整控件大小時應調整路徑大小。描述路徑的點和大小可以表示爲控制尺寸的相對分數。通過模板綁定更改路徑屬性

這裏是模板的摘錄:

<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> 

開始和結束的類型都是點DependencyProperties,大小類型大小的一個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

你有什麼可能是完成這個最好的方法。

另一種方法是構建一個自定義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>