通常情况下,您可以在ItemContainerStyle中添加这样的内容,以免每次需要应用DataTemplate本身。虽然这对ListBox来说很简单,您可以在其中修改ListBoxItem的模板,但不幸的是,基础ItemsControl仅使用ContentPresenter作为其容器,因此无法以相同的方式进行模板化。
如果你真的希望这是可重用的,我建议你将它包装到一个新的自定义ItemsControl中,您可以放入其中以替换标准的一个,而无需修改正在使用的特定DataTemplate。这也可以让你包装属性,否则你将在外部创建属性作为附属的道具和控制本身的删除命令。
显然,删除逻辑和视觉造型还没有在这里做,但这应该让你开始:
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>