通常,您会在ItemContainerStyle中添加类似的内容,以免每次应用此内容时都会弄乱DataTemplate本身。虽然这对于可以修改ListBoxItem模板的ListBox很简单,但很遗憾,基本ItemsControl仅使用ContentPresenter作为其容器,因此不能以相同的方式进行模板化。
显然,删除逻辑和视觉样式尚未在此处完成,但这将使您开始:
public class DeleteItemsControl : ItemsControl
{
public static readonly DependencyProperty CanDeleteProperty = DependencyProperty.Register(
"CanDelete",
typeof(bool),
typeof(DeleteItemsControl),
new UIPropertyMetadata(null));
public bool CanDelete
{
get { return (bool)GetValue(CanDeleteProperty); }
set { SetValue(CanDeleteProperty, value); }
}
public static RoutedCommand DeleteCommand { get; private set; }
static DeleteItemsControl()
{
DeleteCommand = new RoutedCommand("DeleteCommand", typeof(DeleteItemsControl));
DefaultStyleKeyProperty.OverrideMetadata(typeof(DeleteItemsControl), new FrameworkPropertyMetadata(typeof(DeleteItemsControl)));
}
protected override DependencyObject GetContainerForItemOverride()
{
return new DeleteItem();
}
protected override bool IsItemItsOwnContainerOverride(object item)
{
return item is DeleteItem;
}
}
public class DeleteItem : ContentControl
{
static DeleteItem()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DeleteItem), new FrameworkPropertyMetadata(typeof(DeleteItem)));
}
}
这将在Generic.xaml中进行,或者您可以像在应用程序中应用普通样式一样应用它们:
<Style TargetType="{x:Type local:DeleteItemsControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DeleteItemsControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type local:DeleteItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DeleteItem}">
<Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<DockPanel>
<Button Command="local:DeleteItemsControl.DeleteCommand" Content="X" HorizontalAlignment="Left" VerticalAlignment="Center"
Visibility="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:DeleteItemsControl}}, Path=CanDelete, Converter={StaticResource BooleanToVisibilityConverter}}"/>
<ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>