开发者

How to avoid recursive dependency properties

I have a class LineG inherited from a shape which will draw a simple line between two points.. I did that simply by adding two dependency properties StartPointProperty and EndPointProperty... Lastly I want to add another functionality which is MidPoint, so when I draw the line there will be a midPoint in the middle of the line. When I drag the StartPoint or EndPoint the shape will be redrawn, and when I drag the MidPoint the shape will translate depending on the MidPoint change...

private static void PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            LineG lineG = (LineG)d;
            if (e.Property.Name == "StartPoint")
            {

            }
            else if (e.Property.Name == "EndPoint")
            {

            }
            else //if MidPoint
            {
                Point p1 = (Point)e.OldValue;
                Point p2 = (Point)e.NewValue;
                double offsetX = p2.X - p1.X;
                double offsetY = p2.Y - p1.Y;

                lineG.StartPoint = new Point(lineG.StartPoint.X + offsetX, lineG.StartPoint.Y + offsetY);
                lineG.EndPoint = new Point(lineG.EndPoint.X + offsetX, lineG.EndPoint.Y + offsetY);
                lineG.MidPoint = GeneralMethods.MidPoint(lineG.StartPoint, lineG.EndPoint);
            }

            lineG.InvalidateMeasure();
        }

protected override Ge开发者_Go百科ometry DefiningGeometry
        {
            get
            {
                lg.StartPoint = StartPoint;
                lg.EndPoint = EndPoint;
                return lg;
            }
        }


In such cases you can add an int counter to each operation in your class that you increment during processing. You don't do something if the counter is not 0. Example:

private int _suspendCalculation;

private static void OnPropertyChanged(..)
{
    if (_suspendCalculation > 0) return;
    _suspendCalculation++;
    try
    {
        CalculateAndSetOtherProperty();
    }
    finally
    {
        _suspendCalculation--;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜