c# – 根据鼠标位置移动wpf按钮但闪烁
作者:互联网
我尝试根据鼠标位置移动按钮,但是当按钮移动时它会闪烁.请找到下面的代码,
在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;
}
}
任何人请提供您的建议?
解决方法:
您的“闪烁”是由PreviewMouseMove处理程序中的转换引起的.
您正在使用鼠标相对于Button控件的位置来变换控件的X和Y位置,每次应用变换时都会更改.每次按钮位置改变时,您的Mouse.GetPosition(发送者为按钮).X& Y将返回不同的值,导致按钮再次更改位置,依此类推.
解决这个问题的一种方法是从父元素(例如Grid,Canvas,具有固定位置)获取鼠标位置:
<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;
}
}
这不是世界上最漂亮的东西,因为它会从左上方“抓住”按钮,但你可以调整位置以获得你想要的行为.
祝好运.
编辑:如果您不想显式命名要用于相对位置的元素,则应该能够通过查询发送方对象来选择直接父级:
transform.X = Mouse.GetPosition((sender as Button).Parent as FrameworkElement).X;
标签:c,wpf,silverlight,wpf-controls 来源: https://codeday.me/bug/20190625/1283669.html