我是一名有用的助手,可以为您翻译文本。
我有一个简单代码的问题。我寻找了几个小时的解决方案,但没有效果。我有一个画布和矩形。如果光标在外面,我会移动矩形,委托pMouseMove只会触发每个像素一次。相反,如果光标在矩形上,委托将每个像素触发两次。我想让它只运行一次,就像在矩形外面一样,怎么做?
XAML:
我有一个简单代码的问题。我寻找了几个小时的解决方案,但没有效果。我有一个画布和矩形。如果光标在外面,我会移动矩形,委托pMouseMove只会触发每个像素一次。相反,如果光标在矩形上,委托将每个像素触发两次。我想让它只运行一次,就像在矩形外面一样,怎么做?
XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Canvas x:Name="Can" Height="257" Width="503" Background="Gray">
<TextBox Name="tb" Width="77" Height="20" Canvas.Left="0" Canvas.Top="-21"/>
</Canvas>
</Window>
代码后台:
public partial class MainWindow : Window
{
Rectangle rect = new Rectangle();
private static int i;
private static string s;
public MainWindow()
{
InitializeComponent();
rect.Height = 50;
rect.Width = 50;
rect.Fill = Brushes.Black;
Can.Children.Add(rect);
Can.PreviewMouseMove += pMouseMove;
}
private void pMouseMove(object sender, MouseEventArgs e)
{
//cursor over Rectangle
Canvas.SetTop(rect, e.GetPosition(Can).Y + 10);
Canvas.SetLeft(rect, e.GetPosition(Can).X + 10);
//cursor outside Rectangle
//Canvas.SetTop(rect, e.GetPosition(Can).Y - 10);
//Canvas.SetLeft(rect, e.GetPosition(Can).X - 10);
//Counter
i++;
tb.Text = i.ToString();
//e.Handled = true;
}
}
非常抱歉我的英语不太好