Ser*_*erG 4 data-binding wpf binding drawing shapes
我有一个由其边界点指定的可观察的线段集合.如何绑定它以在画布上绘制线条?
我已经看到了只使用一个点定义位置的形状解决方案.但是为了将这种方法应用于线条,它需要在坐标上进行笨拙的预计算以获得外部矩形的位置并使线条坐标相对于它.有没有办法避免它?
小智 13
这是一个如何做到的例子:
该行定义如下:
public class Line
{
public Point From { get; set; }
public Point To { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,行是静态的,即如果更新From和To位置,UI将不会更新.如果要更新UI,则必须INotifyPropertyChanged为Line该类实现.
此示例显示如下所示的窗口:
