WPF - 如何以编程方式在自定义控件之间画线

WPF - How to draw lines between custom controls programmatically

所以我正在尝试制作一个程序,允许用户使用 WPF 中具有不同功能的模块设计简单的程序。

我为我的模块创建了自定义控件,如下所示:

    <Border Height="75" Width="150" BorderThickness="1" BorderBrush="Black">
    <Grid Background="Gray" Height="75" Width ="150">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="2*"/>
        </Grid.RowDefinitions>
        <Label Content="Double" FontSize="12" Grid.Row="0" HorizontalContentAlignment="Center" Background="Aquamarine"/>
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition Width="3*"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Button Name="IncomingConnection" Height="15" Width="15" Background="Black" Margin="5" VerticalAlignment="Top" HorizontalAlignment="Left"/>

            <Button Name="OutgoingConnection" Grid.Column="2" Height="15" Width="15" VerticalAlignment="Top" Background="Black" Margin="5" HorizontalAlignment="Right"/>
            <Button Name="OutgoingData" Grid.Column="2" Height="15" Width="15" VerticalAlignment="Bottom" Background="Aquamarine" Margin="5" HorizontalAlignment="Right"/>
        </Grid>
    </Grid>
</Border>

无论如何,我希望能够单击这些按钮之一(incomingConnection 或 outgoingConnection),并用一条线连接这两个按钮。

其他信息:自定义控件全部放置在拇指内,因此可以四处拖动。一切都在 canvas 上。我不想在控件之间创建一条线,而是在控件上的按钮之间创建一条线。

非常感谢!

对于包含两个端点的 x 和 y 坐标的线,我会有一个 class。我会将每一行的实例放入视图模型的列表中。然后使用绑定到 属性 的 ItemsControlCanvas 作为模板。然后,您可以使用 WPF Line 控件作为 ItemsControlItemTemplate。您可以将 Line 控件的 X1Y1X2Y2 绑定到在以下位置创建的行 class 的端点属性开始。

使用该设置,您所要做的就是将行 class 的实例添加到列表中,它们将自动显示在 Canvas.