好吧,因为除了熟悉C#和WPF之外别无他法,我决定使用可视化图形制作一些简单的应用程序。所以我想把“节点”放在画布上,移动它,通过边缘e.t.c连接。
但我不知道如何检测是否点击了某个“节点”。
我注意到.MouseDown
对象中有Ellipse
但在这种情况下不知道如何使用它(只有if (ellipse.MouseDown)
是正确的)
XAML:
<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>
cs code:
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
}
}
}
}
}
答案 0 :(得分:3)
您可以使用IsMouseOver Property
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;
}
我更喜欢后者。