我正在使用以下 WPF
<Button Style="{DynamicResource NoChromeButton}" x:Name="cmdImage" Grid.Row="1" Margin="10" MouseDoubleClick="cmdImage_MouseDoubleClick" MouseDown="imgMain_MouseDown_1" MouseMove="imgMain_MouseMove_1" MouseUp="imgMain_MouseUp_1">
<Grid x:Name="ImageGrid">
<Image x:Name="imgMain" Panel.ZIndex="0" />
<Button x:Name="rectBounds" Template="{StaticResource DesignerItemTemplate}" Visibility="Hidden" IsVisibleChanged="Button_IsVisibleChanged" Panel.ZIndex="1" />
</Grid>
</Button>
奇怪的是,最外层按钮的MouseUp
、MouseDown
和MouseMove
事件甚至不会触发ImageSource
,如果Image
不是null
(加载了图像)。
我尝试将它们移至Image
控件。它们确实触发了,但行为出乎意料。
private void imgMain_MouseDown_1(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(ImageGrid);
rect = new Rectangle
{
Margin =
new Thickness(e.GetPosition(ImageGrid).X, e.GetPosition(ImageGrid).Y,
ImageGrid.ActualWidth - e.GetPosition(ImageGrid).X,
ImageGrid.ActualHeight - e.GetPosition(ImageGrid).Y),
Stroke = Brushes.Black,
StrokeThickness = 1.0
};
ImageGrid.Children.Add(rect);
Panel.SetZIndex(rect, 2);
}
private void imgMain_MouseMove_1(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Released || rect == null)
return;
Point pos = e.GetPosition(ImageGrid);
double x = Math.Min(pos.X, startPoint.X);
double y = Math.Min(pos.Y, startPoint.Y);
double w = Math.Max(pos.X, startPoint.X) - x;
double h = Math.Max(pos.Y, startPoint.Y) - y;
rect.Margin = new Thickness(x, y, ImageGrid.ActualWidth - x - w, ImageGrid.ActualHeight - y - h);
}
private void imgMain_MouseUp_1(object sender, MouseButtonEventArgs e)
{
rect = null;
}
按照所有明显的规则,应该会出现一个可拖动的矩形,一旦松开鼠标按钮就会消失。它没有。有趣的是,当我更改 的可见性时rectBounds
,会出现一个矩形。