将线条集合绑定到 WPF 中的画布 [英] Bind collection of lines to canvas in WPF

查看:24
本文介绍了将线条集合绑定到 WPF 中的画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由其边界点指定的线段的可观察集合.如何绑定它以在画布上绘制线条?

I have an observable collection of line segments specified by its boundary points. How can I bind it to draw the lines on a canvas?

我已经看到了解决方案,用于仅使用一个点来定义位置的形状.但是为了将这种方法应用于线,它需要对坐标进行笨拙的预计算以获得外部矩形的位置并相对于它制作线坐标.有什么办法可以避免吗?

I have seen the solution for shapes using only one point to define the position. But for applying this approach to lines it need awkward precomputations on coordinates to get the position of outer rectangle and make line coordinates relative to it. Is there a way to avoid it?

推荐答案

下面是一个例子:

该行定义如下:

public class Line
{
    public Point From { get; set; }

    public Point To { get; set; }
}

MainWindow.xaml:

MainWindow.xaml:

<Window x:Class="WpfApplication20.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="300">
    <ItemsControl ItemsSource="{Binding Lines}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Line X1="{Binding From.X}" Y1="{Binding From.Y}"
                      X2="{Binding To.X}" Y2="{Binding To.Y}"
                      Stroke="DarkGray" StrokeThickness="3"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Window>

MainWindow.xaml.cs:

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public ObservableCollection<Line> Lines { get; private set; }

    public MainWindow()
    {
        Lines = new ObservableCollection<Line>
        {
            new Line { From = new Point(100, 20), To = new Point(180, 180) },
            new Line { From = new Point(180, 180), To = new Point(20, 180) },
            new Line { From = new Point(20, 180), To = new Point(100, 20) },
            new Line { From = new Point(20, 50), To = new Point(180, 150) }
        };

        InitializeComponent();
        DataContext = this;
    }
}

在上面的示例中,这些行是静态的,即如果您更新 FromTo 位置,UI 将不会更新.如果您希望 UI 更新,您必须为 Line 类实现 INotifyPropertyChanged.

In the above example, the lines are static, i.e. if you update the From and To positions, the UI will not update. If you want the UI to update, you must implement INotifyPropertyChanged for the Line class.

此示例显示了一个如下所示的窗口:

This sample shows a window that looks like this:

这篇关于将线条集合绑定到 WPF 中的画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆