【问题标题】:Change Path properties via template binding通过模板绑定更改路径属性
【发布时间】:2011-05-20 06:48:37
【问题描述】:

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

这是模板的摘录:

<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 类型的 DependencyProperty,Size 是 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 );
}

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

【问题讨论】:

    标签: wpf templates data-binding controltemplate templatebinding


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 2014-10-20
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      相关资源
      最近更新 更多