2010-08-02 66 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);  


    } 
}