在连接的节点之间绘制线条

时间:2017-06-17 15:39:18

标签: c# wpf xaml mvvm itemscontrol

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

项目详情:我在Visual Studio 2010中使用WPF,XAML,C#和MVVM模式。

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

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

enter image description here

有五个项目,在代码中,N1项目应按行链接到N3,N4和N5项目。 N1到N3线看起来很好,但另外两条线是偏移的。如果你要将它们移动起来,它们会很好地将这些项目链接在一起。

你可能会考虑的第一件事是Canvas中线条的坐标,我已经这样做了。

请查看此图片:

enter image description here

我在与Line相同的区域内向XAML添加了一个TextBlock,并将其Text绑定到Line的StartingPoint。如果图像很小,可能很难看到这里,但我可以告诉你,这里的两条线的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);
                }
            }
        }
    }

2 个答案:

答案 0 :(得分:5)

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

  • 仅包含数据的Node类,使用属于视图的(几何)类型实现明确分离
  • 每次NodeToPathDataConverter NodeList事件被提出时,PropertyChanged负责重新绘制连接线。
  • DragDeltaCommand更新被拖动的Node后面的Thumb数据,之后会引发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);
        }
    }
}

启动时的情况

startup

拖动节点n1

之后

dragged

答案 1 :(得分:1)

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

首先,坐标是相对于父母的。您应该确保每个绘图使用相同的父控件,或者使用$sting_new = 'bla bla bla <a href="some_new_url">some text</a> bla bla bla <a href="some_new_url2">some text 2</a> bla bla bla <a href="some_new_url3">some text 3 3</a>'; 将其推送到正确的位置。

其次,RenderTransform默认面板始终为<ItemsControl>,即使其父级为<StackPanel>。因此,您的第一个模板将每个节点的行与<Canvas>中的ContentControl不同,每个节点都有自己的原点。

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

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

或多或少,你应该得到类似的东西:

ObservableCollection

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