2010-07-23 147 views
0

我有一個類LineG繼承了一個形狀,將在兩點之間繪製一條簡單的線..我通過添加兩個依賴項屬性StartPointProperty和EndPointProperty來做到這一點......最後我想添加另一個功能是MidPoint,所以當我繪製線時,線的中間會出現一個midPoint。 當我拖累:起點或端點的形狀將重繪,當我拖動中點形狀將根據中點變化翻譯...如何避免遞歸依賴屬性

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 Geometry DefiningGeometry 
     { 
      get 
      { 
       lg.StartPoint = StartPoint; 
       lg.EndPoint = EndPoint; 
       return lg; 
      } 
     } 
+1

你的問題是?我不明白標題與問題的文本是如何相關的... – 2010-07-23 21:10:33

+0

我很抱歉,我真的很頭痛...... 我的問題是當我改變StartPoint或EndPoint時,它會改變MidPoint ...並且當我改變MidPoint時,它必須改變StartPoint和EndPoint,但是這會進入遞歸狀態......當我改變StartPoint時,MidPoint將改變,而另一方面MidPoint將改變StartPoint等...如何解決這個問題... – 2010-07-24 11:01:37

回答

1

在這種情況下,您可以添加一個int計數器每在你的班級中操作,你在處理過程中增加。例如:

 
private int _suspendCalculation; 

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