有没有办法避免产生ContentPresenter
that ItemsControl
将我的物品包裹起来?我的ItemsControl
绑定到 VM 属性,我正在使用DataTemplate
在我的 ItemControl 的资源中(没有x:Key
)来自定义我的集合对象的外观。这一切都工作正常,但通过 Snoop 检查显示我的所有集合对象都包装在里面ContentPresenter
s 而不是直接添加到面板中。这一事实给我带来了一些其他问题。有没有办法避免额外的包装?
这是 XAML:
<ItemsControl ItemsSource="{Binding Path=Children}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type vm:Ellipse}">
<Ellipse Fill="{Binding Fill}" Stroke="{Binding Stroke}" />
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Focusable="true" Margin="10" FocusVisualStyle="{x:Null}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding XLoc}" />
<Setter Property="Canvas.Top" Value="{Binding YLoc}" />
<Setter Property="Canvas.ZIndex" Value="{Binding ZOrder}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
您可以创建派生的 ItemsControl 并覆盖其GetContainerForItemOverride https://msdn.microsoft.com/en-us/library/aa346422(v=vs.110).aspx method:
public class MyItemsControl : ItemsControl
{
protected override DependencyObject GetContainerForItemOverride()
{
return new Ellipse();
}
}
您的 ItemsControl XAML 不会设置ItemTemplate
不再,并且有一个ItemContainerStyle
直接瞄准椭圆:
<local:MyItemsControl ItemsSource="{Binding Items}">
<local:MyItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas/>
</ItemsPanelTemplate>
</local:MyItemsControl.ItemsPanel>
<local:MyItemsControl.ItemContainerStyle>
<Style TargetType="Ellipse">
<Setter Property="Width" Value="100"/>
<Setter Property="Height" Value="100"/>
<Setter Property="Fill" Value="{Binding Fill}"/>
<Setter Property="Stroke" Value="{Binding Stroke}"/>
<Setter Property="Canvas.Left" Value="{Binding XLoc}"/>
<Setter Property="Canvas.Top" Value="{Binding YLoc}"/>
<Setter Property="Panel.ZIndex" Value="{Binding ZOrder}"/>
</Style>
</local:MyItemsControl.ItemContainerStyle>
</local:MyItemsControl>
请注意,为了绘制以 XLoc 和 YLoc 为中心的椭圆,您应该将 Ellipse 控件替换为带有 EllipseGeometry 的 Path。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)