2012-04-18 54 views
6

我有一個自定義面板,用於繪製選擇效果;但有時它不清除以前的矩形,如果鼠標在屏幕足夠大(跨兩個顯示器)時來回移動,是WPF錯誤還是限制?你知道如何解決這個問題嗎?提前致謝。WPF UIElement刷新錯誤?

簡化代碼如下所示

public class CustomPanel : Panel 
{ 
    private Rectangle _rectangle; 

    public CustomPanel() 
    { 
     this._rectangle = new Rectangle(); 
     this._rectangle.StrokeThickness = 3; 
     this._rectangle.Stroke = new SolidColorBrush(Color.FromArgb(220, 0, 0, 0)); ; 
     this.Children.Add(this._rectangle); 
    }    

    protected override Size MeasureOverride(Size availableSize) 
    { 
     this._rectangle.Measure(availableSize); 
     return this._rectangle.DesiredSize; 
    } 

    protected override Size ArrangeOverride(Size finalSize) 
    { 
     if (!finalSize.IsEmpty) 
     { 
      this._rectangle.Arrange(new Rect(new Point(0, 0), finalSize)); 
     } 
     return finalSize; 
    } 
}   

,我把它放在一個網格,鼠標移動過程中失效,就像這樣

void OnMouseMove(object sender, MouseEventArgs e) 
    { 
     var point = e.GetPosition(this); 
     var size = new Size(point.X>=0? point.X:0, point.Y>=0? point.Y:0); 
     this.Selection.Measure(size); 
     this.Selection.Arrange(new Rect(size)); 

    } 

,結果看起來像下面的圖片 enter image description here

+0

什麼是選擇? – gliderkite 2012-04-18 16:16:21

+0

我的意思是,該矩形將用於繪製選擇邊框。我們有一個非常複雜的控制,並使用與上面類似的代碼來繪製選擇邊框,這是否有意義? – Hiber 2012-04-19 01:07:19

+0

兩種代碼氣味:mousemove不調用基本實現,並且mousemove不應該是使佈局無效的wpf方法之一。嘗試在更改選擇後在mousemove中手動使佈局無效。 (InvalidateVisual()) – 2012-05-31 15:01:10

回答

1

試試UIElement.InvalidateVisual();