【问题标题】:ItemsControl ignores DataTemplates in ResourcesItemsControl 忽略资源中的 DataTemplates
【发布时间】:2015-07-14 20:33:30
【问题描述】:

我想将多个类型的集合绑定到画布中显示的 ItemsControl。到目前为止,我的代码如下:

<ItemsControl ItemsSource="{Binding Path=Objects}">
     <ItemsControl.Resources>
         <DataTemplate DataType="self:CalibrationRectangle">
             <Rectangle Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Width="{Binding Width}" Height="{Binding Height}" />
         </DataTemplate>
         <DataTemplate DataType="self:PolygonVM">
             <Polygon Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Points="{Binding Points}" />
         </DataTemplate>
     </ItemsControl.Resources>
     <ItemsControl.ItemsPanel>
         <ItemsPanelTemplate>
             <Canvas Background="Red" />
         </ItemsPanelTemplate>
     </ItemsControl.ItemsPanel>
     <!--<ItemsControl.ItemTemplate>
         <DataTemplate DataType="self:CalibrationRectangle">
             <Rectangle Fill="{Binding Path=Color, Converter={StaticResource ColorToBrushConverter}}" Width="{Binding Width}" Height="{Binding Height}" />
         </DataTemplate>
     </ItemsControl.ItemTemplate>-->
     <ItemsControl.ItemContainerStyle>
         <Style>
             <Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
             <Setter Property="Canvas.Left" Value="{Binding Path=X}" />
         </Style>
     </ItemsControl.ItemContainerStyle>
</ItemsControl>

在这种代码状态下,资源中的 DataTemplates 被完全忽略,而是将对象表示为字符串。 相反,如果我使用注释掉的行并在 ItemsControl.ItemsTemplate 中定义 DataTemplate 它可以工作。但是,由于我需要多个 DataTemplates(每种类型一个),这不是解决方案。

这里有什么问题?为什么资源中的 DataTemplates 不起作用?

感谢任何想法:)

【问题讨论】:

  • self:CalibrationRectangleselfPolygonVM 是什么?因为在我看来,您正在将您的 DataTemplate 应用于您的 ItemsControl 中未使用的类型
  • 这些只是一些自己的类型,具有绑定字段作为属性。它们都有相同的父类型,称为 DrawableVM。绑定的集合 Objects 只是一个 ObservableCollection。所以我的 ItemsControl 应该使用这些类型,还是我得到了一些破旧的东西?

标签: c# wpf xaml datatemplate itemscontrol


【解决方案1】:

此时您的目标是 XML 元素名称。如果要定位类型,则需要使用 {x:Type ...} 并替换

<DataTemplate DataType="self:CalibrationRectangle">

<DataTemplate DataType="{x:Type self:CalibrationRectangle}">

来自MSDN

要引用类的类型名称,请使用 x:Type 标记扩展。如果模板用于 XML 数据,则此属性包含 XML 元素名称。

【讨论】:

  • 谢谢 :) 现在可以使用了。但是你能解释一下这两者之间的区别是什么吗?
  • 我刚刚编辑了我的答案以添加更多信息,但基本上没有你的目标 XML 元素名称
猜你喜欢
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2022-06-29
相关资源
最近更新 更多