检测画布元素上的鼠标下移事件
本文关键字:鼠标 事件 布元素 元素 检测 | 更新日期: 2023-09-27 18:18:31
好吧,因为我没有什么比熟悉c#和WPF更好的事情要做,我决定做一些简单的应用程序与图形与可视化。所以我想把"节点"放在画布上,移动它,通过边连接,等等。但我不知道如何检测是否有"节点"被点击。我注意到Ellipse
对象中有.MouseDown
,但不知道如何使用它(只是if (ellipse.MouseDown)
不正确)在这种情况下
<Window x:Class="GraphWpf.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="View" Height="400" Width="700" ResizeMode="NoResize">
<Grid>
<Canvas x:Name="canvas" MouseDown="Canvas_MouseDown" Background="#227FF2C5" Margin="0,0,107,0" />
<CheckBox Content="Put nodes" Height="32" HorizontalAlignment="Left" Margin="591,67,0,0" Name="putNodes" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>
c代码:
public partial class View : Window
{
public View()
{
InitializeComponent();
}
private Point startPoint;
private Ellipse test;
List<Ellipse> nodesOnCanv = new List<Ellipse>();
private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
startPoint = e.GetPosition(canvas);
if ((bool)putNodes.IsChecked)
{
test = new Ellipse();
test.Fill = new SolidColorBrush(Colors.Blue);
test.Width = 20;
test.Height = 20;
var x = startPoint.X;
var y = startPoint.Y;
Canvas.SetLeft(test, x);
Canvas.SetTop(test, y);
canvas.Children.Add(test);
nodesOnCanv.Add(test);
}
else {
foreach(Ellipse element in nodesOnCanv){ //such statment is incorrect
if (element.MouseDown()) {
//do something
}
}
}
}
}
你可以使用IsMouseOver属性
foreach (Ellipse element in nodesOnCanv)
{
if (element.IsMouseOver)
{
element.Fill = Brushes.Red;
}
}
或处理每个节点的MouseDown
test = new Ellipse();
test.MouseDown += new MouseButtonEventHandler(test_MouseDown);
.
void test_MouseDown(object sender, MouseButtonEventArgs e)
{
(sender as Ellipse).Fill = Brushes.Red;
}
我更喜欢后者。