在连接的节点之间画线

The*_*ner 1 c# wpf xaml itemscontrol mvvm

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

项目详细信息:我在Visual Studio 2010中使用WPF,XAML,C#和MVVM模式.

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

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

在此输入图像描述

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

你可以考虑的第一件事是画布中线条的坐标,我已经这样做了.

请查看此图片:

在此输入图像描述

我在与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>
Run Code Online (Sandbox Code Playgroud)

现在,在下面,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>
Run Code Online (Sandbox Code Playgroud)

我这里有两个部分; 两个单独的ItemsControls,目的略有不同.我认为这是可以的,虽然假设可能是我在第一个实例中结束这个问题的方式.

现在接下来的部分是一些背后的代码,我认为,主要部分是OnDragDelta; 用于在Canvas周围拖动项目的事件处理程序:

void OnDeltaDrag(DragDeltaEventArgs e)
    {
        CanvasLeft += e.HorizontalChange;
        CanvasTop += e.VerticalChange;

        UpdateLines();
    }
Run Code Online (Sandbox Code Playgroud)

然后,当然,'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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Fun*_*unk 5

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

  • Node仅包含数据的类,使用属于视图的(几何)类型实现明确分隔
  • NodeToPathDataConverter负责重绘的连接线的,每当NodeList PropertyChanged事件被引发.
  • A 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" }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

启动时的情况

启动


拖动节点n1后

拖