通常情況下,您可以在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>