c# - 在连接的节点之间画线

标签 c# wpf xaml mvvm itemscontrol

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

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

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

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

enter image description here

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

您可能首先考虑的是 Canvas 中线条的坐标,我已经做到了这一点。

请查看此图片:

enter image description here

我将一个 TextBlock 添加到线所在区域内的 XAML,并将其文本绑定(bind)到线的起始点。如果图像很小,这里可能很难看清,但我可以告诉你,这里两条线的 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);
                }
            }
        }
    }

最佳答案

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

  • Node 类仅包含数据,实现与属于 View 的(几何)类型的明确分离
  • NodeToPathDataConverter 负责重绘连接线,每次 NodeList PropertyChanged 事件被引发。
  • 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);
        }
    }
}

启动时的情况

startup


拖动节点n1后

dragged

关于c# - 在连接的节点之间画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606368/

相关文章:

c# - 使用插件将字段设置为只读

c# - Marshal.GetActiveObject ("Outlook.Application") 在使用提升的权限进行调试时抛出 MK_E_UNAVAILABLE

c# - Entity Framework TPC 外键关系

c# - 如何在 WPF 的一个 XAML 文件中添加多个类文件

c# - 菜单的快捷键在 prism 的 wpf 中不起作用

c# - 获取表中的最新版本并将它们放入列表中

.net - 如何使用 WPF 确定默认打印机?

windows-phone-7 - 使用 ExpanderView & Binding 时页面加载缓慢(Windows Phone 7)

c# - 如何播放导入到C#WPF项目中的声音?

c# - XP 中的 XAML 用户控件问题