在ItemsControl中避免使用ContentPresenter

dot*_*NET 5 wpf xaml datatemplate itemscontrol

有没有一种方法,以避免产生的ContentPresenterItemsControl封装在我的项目?我ItemsControl绑定了一个VM属性,我DataTemplate在我的ItemControl的资源(没有x:Key)中使用了一个来自定义我的集合对象的外观.这一切都很好,但通过Snoop检查显示我的所有集合对象都包含在ContentPresenters中,而不是直接添加到Panel中.这个事实为我创造了一些其他问题.有没有办法避免额外的包装?

这是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>
Run Code Online (Sandbox Code Playgroud)

Cle*_*ens 6

您可以创建一个派生的 ItemsControl 并覆盖其GetContainerForItemOverride方法:

public class MyItemsControl : ItemsControl
{
    protected override DependencyObject GetContainerForItemOverride()
    {
        return new Ellipse();
    }
}
Run Code Online (Sandbox Code Playgroud)

您的 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>
Run Code Online (Sandbox Code Playgroud)

请注意,为了绘制以 XLoc 和 YLoc 为中心的椭圆,您应该将 Ellipse 控件替换为带有 EllipseGeometry 的 Path。