DataTemplates to display a collection of Points as Ellipses in WPF

半世苍凉 提交于 2019-12-13 16:54:18

问题


In my application, the user is supposed to click over an image, and as he clicks some dots appear. Also he can remove them by right clicking, etc.

So I have a test project composed of a single Window (xaml + codebehind) with a canvas, and I am handling some of its events, as MouseMove and MouseLeftButtonDown which are going to add points to an ObservableCollection<Point> in code behind.

I already have this, what I don't know is how I'm supposed to implement data-templating and databinding so that my grid will contain an ItemsControl and every point will be displayed as a dot (Path with an EllipseGeometry, so that I can set its Center).

I took a look at some tutorials, but most of them have a lot of extra code and I am confused.


回答1:


Here's a simple solution implemented entirely in 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>


来源:https://stackoverflow.com/questions/19797737/datatemplates-to-display-a-collection-of-points-as-ellipses-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!