wpf - DataTemplates 在 WPF 中将点集合显示为椭圆

标签 wpf datatemplate itemscontrol itemsource

在我的应用程序中,用户应该点击图像,当他点击时会出现一些点。他也可以通过右键单击等方式删除它们。

所以我有一个由带有 Canvas 的单个窗口(xaml + 代码隐藏)组成的测试项目,我正在处理它的一些事件,如 MouseMoveMouseLeftButtonDown这将为 ObservableCollection<Point> 添加点数在代码后面。

我已经有了这个,我不知道我应该如何实现数据模板和数据绑定(bind),以便我的网格将包含一个 ItemsControl每个点都将显示为一个点( PathEllipseGeometry ,这样我就可以设置它的 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/

相关文章:

c# - 模板中的 MVVM 绑定(bind)问题(特别是 Expander 控件的 HeaderTemplate)

.net - WPF:当其中一个控件获得焦点时,如何选择 ListBoxItem?

c# - 命名空间中不存在控件

WPF 绑定(bind)到两个属性

使用 Blend 为 ListBox 项目的 DataTemplate 中 IsSelected 的 WPF 触发器

wpf - 对 WPF 项控件中的最后一项使用不同的模板

c# - 如何从 WPF 中的 app.config 获取 List<string> 值集合?

wpf - 绑定(bind)颜色资源?

wpf - 如何从 UserControl 访问父级的 DataContext

c# - XamlWriter 失去绑定(bind) - 好的!但是如何保值呢? (项目控制)