DataTemplates在WPF中将点的集合显示为椭圆 [英] DataTemplates to display a collection of Points as Ellipses in WPF

查看:85
本文介绍了DataTemplates在WPF中将点的集合显示为椭圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,用户应该单击图像,并且在单击时会出现一些点。他也可以通过右键单击等将其删除。

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.

所以我有一个测试项目,该项目由一个带有画布的Window(xaml +代码隐藏)组成,我正在处理它的一些事件,例如 MouseMove MouseLeftButtonDown ,这些事件将向 ObservableCollection< ; point> 后面的代码。

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.

我已经有了这个,我不知道该怎么实现数据-模板和数据绑定,这样我的网格将包含一个 ItemsControl ,并且每个点都将显示为一个点( Path EllipseGeometry ,以便我可以设置其 Center )。

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.

推荐答案

这是一个完全在XAML中实现的简单解决方案:

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>

这篇关于DataTemplates在WPF中将点的集合显示为椭圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆