我的WPF测试应用程序中有以下XAML代码:
<Canvas x:Name="canvas"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
Background="CornflowerBlue" MouseMove="canvas_MouseMove"
MouseLeftButtonUp="canvas_MouseLeftButtonUp"
/>
在我的.cs文件中:
private const int Radius = 10;
private Ellipse _prev;
private void canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (this._prev != null)
canvas.Children.Remove(this._prev);
var pos = e.GetPosition(canvas);
var c = new Ellipse()
{
Height = 2 * Radius,
Width = 2 * Radius,
Fill = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)),
};
double x = pos.X - Radius;
double y = pos.Y - Radius;
Canvas.SetTop(c, y);
Canvas.SetLeft(c, x);
canvas.Children.Add(c);
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Pressed)
{
if (this._prev != null)
canvas.Children.Remove(this._prev);
var pos = e.GetPosition(canvas);
_prev = new Ellipse()
{
Height = 2 * Radius,
Width = 2 * Radius,
Fill = new SolidColorBrush(Color.FromArgb(100, 255, 0, 0)),
};
double x = pos.X - Radius;
double y = pos.Y - Radius;
Canvas.SetTop(_prev, y);
Canvas.SetLeft(_prev, x);
canvas.Children.Add(_prev);
}
}
我想要做的基本上是当用户点击鼠标左键并拖动时,光标后面会出现一个带有一点alpha字母的红色圆圈。当用户释放鼠标时,红色圆圈停留在那里,没有更多的alpha着色。看起来像一个非常简单的任务,但MouseLeftButtonUp事件仅在我释放它之前不拖动鼠标时触发。我在这里做错了什么?
答案 0 :(得分:1)
您总是在canvas_MouseMove函数中删除并添加椭圆到画布。如果你尝试在canvas_MouseMove中改变椭圆的位置,你可以做你想做的事情