根据鼠标位置移动wpf按钮但闪烁

时间:2013-06-25 10:40:44

标签: c# wpf silverlight wpf-controls

我尝试根据鼠标位置移动按钮,但是当按钮移动时它会闪烁。请找到以下代码,

在XAML的代码下面,

        <Button Name="Samplebutton"
                PreviewMouseDown="Samplebutton_PreviewMouseDown"
                PreviewMouseUp="Samplebutton_PreviewMouseUp"
                PreviewMouseMove="Samplebutton_PreviewMouseMove"
                Content="Moving" Width="100" Height="35"/>

CS,

    private bool m_IsPressed = false;

    private void Samplebutton_PreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.ChangedButton == MouseButton.Left)
        {
            m_IsPressed = true;
        }
        else
        {
            m_IsPressed = false;
        }
    }

    private void Samplebutton_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    {
        m_IsPressed = false;
    }

    private void Samplebutton_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (m_IsPressed)
        {
            TranslateTransform transform = new TranslateTransform();
            transform.X = Mouse.GetPosition(sender as Button).X;
            transform.Y = Mouse.GetPosition(sender as Button).Y;
            this.Samplebutton.RenderTransform = transform;
        }
    }

任何人请提供您的建议吗?

2 个答案:

答案 0 :(得分:3)

您的“闪烁”是由PreviewMouseMove处理程序中的转换引起的。

您正在使用鼠标相对于Button控件的位置来变换控件的X和Y位置,每次应用变换时都会更改。每次按钮位置发生变化时,您的Mouse.GetPosition(sender as Button).X&amp; Y将返回不同的值,导致按钮再次更改位置,依此类推。

解决此问题的一种方法是从父元素获取鼠标位置(例如GridCanvas具有固定位置):

<Grid Name="myGrid">
    <Button Name="Samplebutton"
            PreviewMouseDown="Samplebutton_PreviewMouseDown"
            PreviewMouseUp="Samplebutton_PreviewMouseUp"
            PreviewMouseMove="Samplebutton_PreviewMouseMove"
            Content="Moving" Width="100" Height="35"/>
</Grid>

private void Samplebutton_PreviewMouseMove(object sender, MouseEventArgs e)
    {
        if (m_IsPressed)
        {
            TranslateTransform transform = new TranslateTransform();
            transform.X = Mouse.GetPosition(myGrid).X;
            transform.Y = Mouse.GetPosition(myGrid).Y;
            this.Samplebutton.RenderTransform = transform;
        }
    }

这不是世界上最漂亮的东西,因为它会从左上角“抓住”按钮,但你可以调整位置以获得你想要的行为。

祝你好运。

编辑:如果您不想明确命名要用于相对位置的元素,则应该能够通过查询sender对象来选择直接父级:

transform.X = Mouse.GetPosition((sender as Button).Parent as FrameworkElement).X;

答案 1 :(得分:1)

 private void button_PreviewMouseDown_1(object sender, MouseButtonEventArgs e)
    {
        button.CaptureMouse();
    }

    private void button_PreviewMouseUp_1(object sender, MouseButtonEventArgs e)
    {
        button.ReleaseMouseCapture();
    }

    private void button_PreviewMouseMove_1(object sender, MouseEventArgs e)
    {

        if (button.IsMouseCaptured)
        {
            Canvas.SetLeft(button, e.GetPosition(this).X);
            Canvas.SetTop(button, e.GetPosition(this).Y);

        }
    }