我是Silverlight的新手,我正在努力在运行时在屏幕上绘制一个矩形,
我有一个类(SelectionBox),在主页面上,我有一个画布, 当点击该画布时,我有以下函数叫
private void BeginDrawing(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_initXPos = e.GetPosition(drawingArea).X;
_initYPos = e.GetPosition(drawingArea).Y;
_selectionBox = new SelectionBox ();
drawingArea.Children.Add(_selectionBox);
_isDrawing = true;
}
并且通过混合事件(MouseLeftButtonDown)添加了Handler
当鼠标移动时,调用以下方法,也通过Blend事件添加
private void UpdateSelectionBox(object sender, System.Windows.Input.MouseEventArgs e)
{
if(!_isDrawing &&)
return;
double rectWidth, rectHeight, rectXPos, rectYPos;
if (e.GetPosition(drawingArea).X >= _initXPos)
{
rectWidth = e.GetPosition(drawingArea).X - _initXPos;
rectXPos = _initXPos;
}
else
{
rectWidth = _initXPos - e.GetPosition(drawingArea).X;
rectXPos = e.GetPosition(drawingArea).X;
}
if (e.GetPosition(drawingArea).Y >= _initYPos)
{
rectHeight = e.GetPosition(drawingArea).Y - _initYPos;
rectYPos = _initYPos;
}
else
{
rectHeight = _initYPos - e.GetPosition(drawingArea).Y;
rectYPos = e.GetPosition(drawingArea).Y;
}
_selectionBox.Width = Math.Abs(rectWidth - 20);
_selectionBox.Height = Math.Abs(rectHeight - 20);
Canvas.SetLeft(_selectionBox, Math.Abs(rectXPos - 20));
Canvas.SetTop(_selectionBox, Math.Abs(rectYPos - 20));
}
当触发mouseLeftButtonUp时,以下处理程序应该可以工作,
private void StopDrawingAndSelect(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_isDrawing = false;
drawingArea.Children.Remove(_selectionBox);
}
但不幸的是它永远不会触发,我设置了一个断点并尝试调试它但它永远不会达到,我不确定为什么,这是SelectionBox类的XAML
<UserControl
...
<Grid x:Name="LayoutRoot">
<Rectangle Fill="#00F4F4F5" Stroke="Black" StrokeDashArray="1 2"/>
</Grid>
</UserControl>
这是MainPage的XAML
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:SelectionBoxTraining"
x:Class="SelectionBoxTraining.MainPage"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" Background="White">
<Canvas Margin="165,0,0,0" x:Name="drawingArea" MouseLeftButtonDown="BeginDrawing" Background="#FF959FD6" MouseMove="UpdateSelectionBox" MouseLeftButtonUp="StopDrawingAndSelect" />
</Grid>
</UserControl>
请有人帮帮我吗?我尝试了很多事情但是没有用
我希望我能在这里找到帮助,
注意:XAML代码中不包含属性,以节省空间,
谢谢。
答案 0 :(得分:0)
我猜想原因是你的矩形正在获取UP事件并且(不知何故?)没有将它冒泡到画布上。因此,尝试将ishitestvisible设置为false:
private void BeginDrawing(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_initXPos = e.GetPosition(drawingArea).X;
_initYPos = e.GetPosition(drawingArea).Y;
_selectionBox = new SelectionBox ();
_selectionBox.IsHitTestVisible = false;
drawingArea.Children.Add(_selectionBox);
_isDrawing = true;
}
`
答案 1 :(得分:0)
即使我不相信答案,它现在正在运作 但我通过双击Blend的MouseUp事件所改变了OnMouseUp功能,它变成了
private void drawingArea_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_isDrawing = false;
drawingArea.Children.Remove(_selectionBox);
}
有没有人解释导致问题的原因?处理程序的名称是否具有该效果?我很奇怪..