2

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.

heltonbiker
  • 26,657
  • 28
  • 137
  • 252

1 Answers1

7

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>
Mike Strobel
  • 25,075
  • 57
  • 69
  • It worked in the first try! I plan to tweak it a bit, but that's what I was looking for, thanks!! – heltonbiker Nov 05 '13 at 20:19
  • I was setting a RenderTransform at the ellipses themselves (as I already did in the past, I'm sure), but things only worked after setting the Item CONTAINER Style. Tricky WPF! Thanks for the answer! – heltonbiker Mar 22 '17 at 20:46
  • I am pretty new to WPF so it might be a silly question: is it possible to tweak this solution to draw something else to the same canvas? I want to bind a point collection and a rectangle that belong to a canvas contained in a viewbox. So far I came up using a polyline and binding its pointcollection and the rectangle canvas left and top, but polyline is not what I want. I want to see only the points, this solution is great but I could not figure out how to display also my rectangle in the same canvas – giuseppe Mar 27 '17 at 19:31
  • Missing something here... isn't the `` part of a parent *`Control`*? – IAbstract Aug 09 '21 at 04:12