2010-08-02 65 views
1

我想要一個帶圓角矩形的WPF畫布,我可以用鼠標拖動。但是,一旦我嘗試在畫布上捕獲鼠標,我就不會再收到移動事件了。WPF在CaptureMouse()後不發送MouseMove事件;

這是一個「mycanvas」用戶控件,矩形是「foo」用戶控件。在XAML這些(減去前序)是:

mycanvas.xaml:

<Canvas MouseDown="CanvasMouseDown" MouseMove="CanvasMouseMove" MouseUp="CanvasMouseUp" Background="White"> 

    <my:Foo HorizontalAlignment="Left" Canvas.Left="97" Canvas.Top="30" x:Name="m_foo" VerticalAlignment="Top" Height="87" Width="128" /> 
</Canvas> 

foo.xaml:

<Border BorderThickness="2" BorderBrush="Black" CornerRadius="15" Background="Plum"> 
    <Grid> 
     <Label Content="Foo" Height="28" HorizontalAlignment="Left" Margin="6,6,0,0" Name="label1" VerticalAlignment="Top" /> 
    </Grid> 
</Border> 

然後是處理程序是: mycanvas.xaml.cs:

private void CanvasMouseDown(object sender, MouseButtonEventArgs e) 
{ 
    if (e.Source is Foo) 
    { 
     m_moving = e.Source as Foo; 
     CaptureMouse(); 
     e.Handled = true; 
    } 
} 

private void CanvasMouseMove(object sender, MouseEventArgs e) 
{ 
    if (m_moving != null) 
    { 
     Canvas.SetLeft(m_moving, e.GetPosition(this).X); 
     Canvas.SetTop(m_moving, e.GetPosition(this).Y); 
    } 
} 

private void CanvasMouseUp(object sender, MouseButtonEventArgs e) 
{ 
    ReleaseMouseCapture(); 
    m_moving = null; 
} 

MouseDown會發生火災,所以CaptureMouse會被調用(並且因爲我無法再修復選擇應用程序或單擊其中的任何內容!)但MouseMove永遠不會被調用 - 那麼MouseMove事件現在發送到哪裏?

如果我alt選項卡到另一個應用程序,然後現在回去suddendly調用MouseMove和Foo隨鼠標移動。

回答

7

儘量之一:

Mouse.Capture(this, CaptureMode.SubTree); 

m_moving.CaptureMouse(); 
... 
if (m_moving != null) 
{ 
    m_moving.ReleaseMouseCapture(); 
    m_moving = null; 
} 

鼠標事件正由美孚提出的,而不是由畫布,所以當你捕獲鼠標與畫布可以防止它們被提出。

+0

似乎工作。謝謝。 (仍然不太明白爲什麼,但嘿..) – MrPurpleStreak 2010-08-02 14:34:57

1

您可以直接使用窗口MouseMove事件:

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 

     this.MouseMove += MouseEventHandler; 

    } 

    private void MouseEventHandler(Object sender, MouseEventArgs e) 
    { 
     System.Windows.Point position = e.GetPosition(this); 

     Canvas.SetLeft(ElipseElement, position.X-5); 
     Canvas.SetTop(ElipseElement, position.Y-5);  


    } 
}