C# 在连接的节点之间绘制线

C# 在连接的节点之间绘制线,c#,wpf,xaml,mvvm,itemscontrol,C#,Wpf,Xaml,Mvvm,Itemscontrol,概述:我有一个XAML画布控件,在该控件上放置了几个行控件。这些线出现在它们不应该出现的地方,我的结论是,所述线的边界框行为不端。我不访问或更改这些边界框(据我所知) 项目详细信息:我正在使用WPF、XAML、C#和MVVM模式,所有这些都在Visual Studio 2010中 更详细的解释:我的项目是创建一个画布,并在画布上放置用户可以拖动的项目。在一个项目和另一个项目之间绘制线条,以显示视觉链接 要进行可视化,您可以在此处看到图像: 代码中有五个项目,N1项目应通过行链接至N3、N4和N

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

项目详细信息:我正在使用WPF、XAML、C#和MVVM模式,所有这些都在Visual Studio 2010中

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

要进行可视化,您可以在此处看到图像:

代码中有五个项目,N1项目应通过行链接至N3、N4和N5项目。N1到N3的线看起来不错,但其他两条线是偏移的。如果你把它们向上移动,它们会很好地将这些项目连接在一起

你可以考虑的第一件事是画布中的线条的坐标,而我已经这样做了。 请查看此图像:

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

我还认为这可能是一个对齐问题。我没有在我的项目中设置任何路线,所以我认为这可能是问题所在。我改变了我的线条,使其具有不同的对齐方式(水平和垂直)以及项目本身,我没有观察到任何差异

项目详情:

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

<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>
当然,还有“更新线”:

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);
                }
            }
        }
    }
public void UpdateLines()
{
//评估下一个节点。它们的线路需要更改-它们的起点必须与此节点一起移动。
对于(int i=0;i
如果需要将可拖动节点链接到其他节点,则可以执行更简单的操作

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

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

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

然后,您必须从节点到每个相关节点绘制一条线

或多或少,你应该得到如下结果:

<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>


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

如果需要将可拖动节点链接到其他节点,可以做得更简单

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

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

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

然后,您必须从节点到每个相关节点绘制一条线

或多或少,你应该得到如下结果:

<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已经提到, 这导致了堆叠行为。您的解决方案的整体实现看起来很笨拙,但是,我准备了一个
WpfApp
(使用MVVM Light)来展示一种更优雅地处理这个问题的方法

  • 一个只包含数据的
    节点
    类,实现了与视图中(几何体)类型的清晰分离
  • 每次引发
    NodeList
    PropertyChanged
    事件时,负责重新绘制连接线的
    NodePathDataConverter
    <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>
    
    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" }
            };
        }
    }
    
    <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>
    
    /// <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();
        }
    }
    
    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);
            }
        }
    }