在我的应用程序中,用户应该点击图像,当他点击时会出现一些点。他也可以通过右键单击等方式删除它们。
所以我有一个由带有 Canvas 的单个窗口(xaml + 代码隐藏)组成的测试项目,我正在处理它的一些事件,如 MouseMove
和 MouseLeftButtonDown
这将为 ObservableCollection<Point>
添加点数在代码后面。
我已经有了这个,我不知道我应该如何实现数据模板和数据绑定(bind),以便我的网格将包含一个 ItemsControl
每个点都将显示为一个点( Path
和 EllipseGeometry
,这样我就可以设置它的 Center
)。
我看了一些教程,但是大多数都有很多额外的代码,我很困惑。
最佳答案
这是一个完全用 XAML 实现的简单解决方案:
<!-- Bind ItemsSource to the appropriate collection -->
<ItemsControl ItemsSource="{Binding Points}">
<ItemsControl.ItemContainerStyle>
<Style TargetType="FrameworkElement">
<Setter Property="Canvas.Left" Value="{Binding X}" />
<Setter Property="Canvas.Top" Value="{Binding Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="Point">
<Ellipse Fill="Blue"
Width="8"
Height="8"
Margin="-4,-4,4,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
关于wpf - DataTemplates 在 WPF 中将点集合显示为椭圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19797737/