我有一个由边界点指定的可观察线段集合。如何将其绑定以在画布上绘制线条?
我已经看到了仅使用一个点定义位置的形状的solution。但是,如果将这种方法应用于线条,则需要对坐标进行笨拙的预计算,以获取外部矩形的位置,并使线条坐标相对于它。有没有办法避免这种情况?
我已经看到了仅使用一个点定义位置的形状的solution。但是,如果将这种方法应用于线条,则需要对坐标进行笨拙的预计算,以获取外部矩形的位置,并使线条坐标相对于它。有没有办法避免这种情况?
这里是一个示例,说明如何实现它:
该行定义如下:
public class Line
{
public Point From { get; set; }
public Point To { get; set; }
}
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:
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;
}
}
From
和To
的位置,则UI不会更新。如果要使UI更新,必须为Line
类实现INotifyPropertyChanged
。Canvas.Top=0
和 Canvas.Left=0
,即它们都对齐到相同的原点。 - user128300顺便说一下,我通常为了避免使用ItemsControl而使用PolyLine,并简单地绑定一个点集合。在XAML中:
<Polyline Points="{Binding Points}" Stroke="White" StrokeThickness=".1" />
namespace YourNameSpace.ViewModels
{
class MainViewModel : ViewModelBase
{
#region Parameters
private PointCollection points = new PointCollection();
public PointCollection Points
{
get { return points; }
set
{
points = value;
NotifyPropertyChanged("Points");
}
}
public MainViewModel()
{
PointCollection polygonPoints = new PointCollection
{
new Point(10, 50),
new Point(100, 50),
new Point(50, 30),
new Point(75, 100),
new Point(75, 10)
};
this.Points = polygonPoints;
}
}}