gpt4 book ai didi

c# - ItemsControl 忽略资源中的 DataTemplates

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:47 25 4
gpt4 key购买 nike

我想将多种类型的集合绑定(bind)到 Canvas 中显示的 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 不起作用?

任何想法表示赞赏:)

最佳答案

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

<DataTemplate DataType="self:CalibrationRectangle">

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

来自 MSDN :

To refer to the type name of the class, use the x:Type Markup Extension. If the template is intended for XML data, this property contains the XML element name.

关于c# - ItemsControl 忽略资源中的 DataTemplates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com