double typed DependencyProperty不会导致调用MeasureOverride()

时间:2018-04-25 08:17:11

标签: c# wpf dependency-properties

我正在制作一个来自FrameworkElement课程的自定义刻度线指示器。我有一堆属性(附带依赖属性)定义指标的外观和功能,例如OrientationRangeOrientation的类型为OrientationRange的类型为double

从视图模型中更改Orientation会导致调用MeasureOverride()方法,从而允许我定义控件的新维度。但由于某些原因,更改Range属性不会(并且也不会更改其他double类型的属性)。我无法弄清楚原因。有人知道为什么会这样,以及如何让Range属性也调用MeasureOverride()

public class DepthIndicatorTickBar : FrameworkElement
{
    public static readonly DependencyProperty OrientationProperty =
        DependencyProperty.Register("Orientation", typeof(Orientation),
            typeof(DepthIndicatorTickBar),
            new FrameworkPropertyMetadata(Orientation.Horizontal,
                FrameworkPropertyMetadataOptions.AffectsRender));

    public static readonly DependencyProperty RangeProperty =
        DependencyProperty.Register("Range", typeof(double), 
            typeof(DepthIndicatorTickBar), 
            new FrameworkPropertyMetadata((double)100, 
                FrameworkPropertyMetadataOptions.AffectsRender));

    public Orientation Orientation
    {
        get { return (Orientation)GetValue(OrientationProperty); }
        set { SetValue(OrientationProperty, value); }
    }

    public double Range
    {
        get { return (double)GetValue(RangeProperty); }
        set { SetValue(RangeProperty, value); }
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        Console.WriteLine("MeasureOverride");
        // Calculating new size
        return size;
    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        Console.WriteLine("OnRender");
        // Drawing control
    }
}

1 个答案:

答案 0 :(得分:2)

如果要确保依赖项属性的值更改强制执行度量传递并重新呈现,只需组合相应的FrameworkPropertyMetadataOptions标志:

public static readonly DependencyProperty RangeProperty = DependencyProperty.Register(
    nameof(Range),
    typeof(double), 
    typeof(DepthIndicatorTickBar), 
    new FrameworkPropertyMetadata(
        100d, 
        FrameworkPropertyMetadataOptions.AffectsMeasure |
        FrameworkPropertyMetadataOptions.AffectsRender));