通常,您会在 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>