在连接的节点之间画线

Draw lines between connected nodes

概述:我有一个 XAML Canvas 控件,我在上面放置了几个 Line 控件。这些线出现在它们不应该出现的地方,我的结论是这些线的边界框行为不当。我不访问或更改这些边界框(据我所知)。

项目详情:我正在使用 WPF、XAML、C# 和 MVVM 模式,所有这些都在 Visual Studio 2010 年内完成。

更详细的解释:我的项目是创建一个 canvas 并在 canvas 上放置用户可以拖动的项目。在一个项目和另一个项目之间绘制线条,以显示视觉效果 link.

为了形象化,你可以在这里看到一张图片:

有五个项目,在代码中,N1 项目应该按行 link 编辑到 N3、N4 和 N5 项目。 N1 到 N3 线好像没问题,其他两条都偏移了。如果您将它们向上移动,它们会 link 将这些项目很好地组合在一起。

你可能首先考虑的是Canvas内线的坐标,我已经做到了。

请查看这张图片:

我将一个 TextBlock 添加到与线相同区域内的 XAML,并将其文本绑定到线的起点。如果图像很小,这里可能很难看清,但我可以告诉你,这里两条线的 StartingPont 是相同的。然而,我们可以清楚地看到线条不在同一个地方。

我还以为这可能是对齐的问题。我没有在我的项目中设置任何对齐方式,所以我认为这可能是问题所在。我更改了我的线条以具有不同的对齐方式(水平和垂直)以及项目本身,但我没有发现任何差异。

项目更详细:

首先是项目本身的资源。我不认为这会有所作为,但由于我完全没有想法,我不能否认问题可能出在看不见的地方:

<ResourceDictionary>
        <ControlTemplate x:Key="NodeTemplate">
            <Border BorderThickness="2" BorderBrush="LightBlue" Margin="2" CornerRadius="5,5,5,5">
            <StackPanel>
                <TextBlock Text="Test" Background="AntiqueWhite"/>
                <TextBlock Text="{Binding Path=NodeText}" Background="Aqua"/>
                </StackPanel>
                </Border>
        </ControlTemplate>
    </ResourceDictionary>

现在下面是 Canvas 本身,其中包含 ItemsControls:

<Canvas>


    <ItemsControl ItemsSource="{Binding NodeList, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding LineList, UpdateSourceTrigger=PropertyChanged}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>

                            <StackPanel>
                                <Line Stroke="Black" X1="{Binding StartPoint.X}" Y1="{Binding StartPoint.Y}" X2="{Binding EndPoint.X}" Y2="{Binding EndPoint.Y}"  />
                            <!--Path Stroke="Black" Data="{Binding}" Canvas.Left="0" Canvas.Top="0" StrokeMiterLimit="1"/-->
                                <TextBlock Text="{Binding StartPoint}" HorizontalAlignment="Center"/>
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>


    <ItemsControl ItemsSource="{Binding NodeList, UpdateSourceTrigger=PropertyChanged}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Left" Value="{Binding CanvasLeft}"/>
                <Setter Property="Canvas.Top" Value="{Binding CanvasTop}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Thumb Name="myThumb" Template="{StaticResource NodeTemplate}">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="DragDelta">
                            <cmd:EventToCommand Command="{Binding DragDeltaCommand}" PassEventArgsToCommand="True"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Thumb>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Canvas>

我这里有两个部分;两个独立的 ItemsControls,它们的用途略有不同。我认为这没问题,尽管假设可能是我最初如何解决这个问题的。

现在下一部分是一些背后的代码,我认为主要部分是OnDragDelta;将项目拖动到 Canvas:

周围的事件处理程序
void OnDeltaDrag(DragDeltaEventArgs e)
    {
        CanvasLeft += e.HorizontalChange;
        CanvasTop += e.VerticalChange;

        UpdateLines();
    }

当然还有 'UpdateLines':

public void UpdateLines()
    {
        // Assess next nodes. Their lines will need to be changed - their start points will have to move with this node.
        for (int i = 0; i < this.NextNodes.Count; i++)
        {
            this.LineList.ElementAt(i).StartPoint = new Point(this.CanvasLeft, this.CanvasTop);
        }

        // Assess previous nodes. If they have lines to this node, the end points of those
        // lines will need to be moved (more specifically, moved to have the same coords as this).
        foreach (NodeViewModel n in this.PreviousNodes)
        {
            for (int i = 0; i < n.NextNodes.Count; i++)
            {
                if (n.NextNodes.ElementAt(i) == this)
                {
                    n.LineList.ElementAt(i).EndPoint = new Point(this.CanvasLeft, this.CanvasTop);
                }
            }
        }
    }

如果您需要将可拖动节点链接到其他一些节点,您可以做的更简单。

首先,坐标是相对于父对象的。您应该确保每个绘图都使用相同的父控件,或者使用 RenderTransform 将其推送到正确的位置。

其次,<ItemsControl> 默认面板始终是 <StackPanel>,即使其父面板是 <Canvas>。因此,您的第一个模板将每个节点的行堆叠在不同的 ContentControl 中,就像在 ListView 中一样,每个节点都有自己的来源。

我宁愿使用 2 个坐标(CanvasLeft 和 CanvasTop)和相关节点的列表(比如 ObservableCollection)来构建我的节点模型。

然后你必须从你的节点到每个相关节点画一条线。

或多或少,你应该得到这样的结果:

<ItemsControl ItemsSource="{Binding NodeList}">
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <Canvas/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
    <!--using Canvas to avoid stacking of node template and ItemsControl for lines-->
      <Canvas>
        <ItemsControl ItemsSource="{Binding RelatedNodes}" 
                      Canvas.Top="{Binding Path=CanvasTop}" Canvas.Left="{Binding Path=CanvasLeft}">
        <!--every line will have to be drawn from the current node-->
          <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
              <Canvas/>
            </ItemsPanelTemplate>
          </ItemsControl.ItemsPanel>
          <ItemsControl.ItemTemplate>
            <DataTemplate>
            <!--draw a line from the center of the node (0,0) to the center of the related (CanvasTop_of_the_related - CanvasTop_of_the_current)-->
              <Line Stroke="Black" X1="0" Y1="0" X2="{Binding RelativeCanvasLeft}" Y2="{Binding RelativeCanvasTop}" />
            </DataTemplate>
          </ItemsControl.ItemTemplate>
        </ItemsControl>
        <!--drawing the node on top of the lines-->
        <!--use a RenderTransform if needed to "center" on (0,0)-->
        <ContentControl Content="{Binding}" ContentTemplate="{StaticResource NodeTemplate}"/>
      </Canvas>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>

必须有一些方法来避免相对坐标的预先计算依赖于简单的绑定或转换器。

@xum59 已经提到 the default ItemsPanel for an ItemsControl is a StackPanel, 这导致了堆叠行为。您的解决方案的整体实施看起来很尴尬,但是,我准备了一个 WpfApp(使用 MVVM Light)来展示一种更优雅地处理这个问题的方法。

  • A Node class 仅保存数据,实现与属于视图的(几何)类型的明确分离
  • A NodeToPathDataConverter 负责重新绘制连接线,每次引发 NodeList PropertyChanged 事件。
  • A DragDeltaCommand 更新 Thumb 被拖动后的 Node 数据,之后引发 NodeList PropertyChanged 事件。
  • 由于每次拖动都会重新绘制所有线条,因此我选择使用轻量级 StreamGeometry

Node.cs

public class Node : ObservableObject
{
    private double x;
    public double X
    {
        get { return x; }
        set { Set(() => X, ref x, value); }
    }

    private double y;
    public double Y
    {
        get { return y; }
        set { Set(() => Y, ref y, value); }
    }

    public string Text { get; set; }
    public List<string> NextNodes { get; set; }

    public static ObservableCollection<Node> GetSampleNodes()
    {
        return new ObservableCollection<Node>()
        {
            new Node { X = 300, Y = 100, Text = "n1", NextNodes = new List<string> { "n2", "n4", "n5" } },
            new Node { X = 150, Y = 200, Text = "n2", NextNodes = new List<string> { "n3" } },
            new Node { X =  50, Y = 450, Text = "n3" },
            new Node { X = 200, Y = 500, Text = "n4" },
            new Node { X = 700, Y = 500, Text = "n5" }
        };
    }
}

MainWindow.xaml

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:cmd="http://www.galasoft.ch/mvvmlight"
        Title="MainWindow" WindowState="Maximized">
    <Window.Resources>
        <local:NodeToPathDataConverter x:Key="NodeToPathDataConverter" />
        <ControlTemplate x:Key="NodeTemplate">
            <Border BorderThickness="2" BorderBrush="LightBlue" Margin="2" CornerRadius="5,5,5,5">
                <StackPanel>
                    <TextBlock Text="Test" Background="AntiqueWhite" />
                    <TextBlock Text="{Binding Text}" Background="Aqua" TextAlignment="Center" />
                </StackPanel>
            </Border>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ItemsControl ItemsSource="{Binding MainViewModel.NodeList, Source={StaticResource Locator}}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <Canvas/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="ContentPresenter">
                    <Setter Property="Canvas.Left" Value="{Binding X}"/>
                    <Setter Property="Canvas.Top" Value="{Binding Y}"/>
                </Style>
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Canvas>
                        <Path Stroke="Black">
                            <Path.Data>
                                <MultiBinding Converter="{StaticResource NodeToPathDataConverter}">
                                    <Binding Path="MainViewModel.NodeList" Source="{StaticResource Locator}" />
                                    <Binding />
                                </MultiBinding>
                            </Path.Data>
                        </Path>
                        <Thumb Template="{StaticResource NodeTemplate}">
                            <i:Interaction.Triggers>
                                <i:EventTrigger EventName="DragDelta">
                                    <cmd:EventToCommand 
                                        Command="{Binding MainViewModel.DragDeltaCommand, Source={StaticResource Locator}}" 
                                        PassEventArgsToCommand="True"/>
                                </i:EventTrigger>
                            </i:Interaction.Triggers>
                        </Thumb>
                    </Canvas>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Grid>
</Window>

MainWindow.xaml.cs

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

/// <summary>
/// Returns Geometry of line(s) from current node to next node(s)
/// </summary>
public class NodeToPathDataConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var nodes = values[0] as ObservableCollection<Node>;
        Node node = values[1] as Node;
        if (nodes != null && node != null && node.NextNodes != null)
        {
            // Create a StreamGeometry to draw line(s) from the current to the next node(s).
            StreamGeometry geometry = new StreamGeometry();
            using (StreamGeometryContext ctx = geometry.Open())
            {
                foreach (string nextText in node.NextNodes)
                {
                    Node nextNode = nodes.Single(n => n.Text == nextText);
                    ctx.BeginFigure(new Point(0, 0), false /* is filled */, false /* is closed */);
                    ctx.LineTo(new Point(nextNode.X - node.X, nextNode.Y - node.Y), true /* is stroked */, false /* is smooth join */);
                }
            }
            // Freeze the geometry (make it unmodifiable) for additional performance benefits.
            geometry.Freeze();
            return geometry;
        }
        return Binding.DoNothing;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

MainViewModel.cs

public class MainViewModel : ViewModelBase
{
    private ObservableCollection<Node> nodeList;

    public MainViewModel()
    {
        nodeList = Node.GetSampleNodes();
        DragDeltaCommand = new RelayCommand<DragDeltaEventArgs>(e => OnDeltaDrag(e));
    }

    public ICommand DragDeltaCommand { get; private set; }

    public ObservableCollection<Node> NodeList
    {
        get { return nodeList; }
    }

    private void OnDeltaDrag(DragDeltaEventArgs e)
    {
        Thumb thumb = e.Source as Thumb;
        if (thumb != null)
        {
            Node node = (Node)thumb.DataContext;
            node.X += e.HorizontalChange;
            node.Y += e.VerticalChange;

            RaisePropertyChanged(() => NodeList);
        }
    }
}

启动时的情况


拖动节点n1后