WPF的ListBoxItem样式覆盖了我的ItemTemplate
本文关键字:我的 ItemTemplate 覆盖 样式 ListBoxItem WPF | 更新日期: 2023-09-27 18:01:21
我有一个列表框,它绑定到具有两个属性的对象列表Items
: Name
和IP
。
我想为每个项目设置一个工具提示,显示悬停时的IP地址,所以我这样做了:
<ListBox ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" ToolTip="{Binding IP}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
这工作。然而,当我应用以下样式时,似乎我的<DataTemplate>
被完全忽略了,列表只是在我的对象上调用ToString()
,工具提示根本没有显示。
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="Bd"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="true">
<Grid>
<GridViewRowPresenter x:Name="gridrowPresenter"
Content="{TemplateBinding Property=ContentControl.Content}" />
<ContentPresenter x:Name="contentPresenter"
Content="{TemplateBinding Property=ContentControl.Content}" Visibility="Collapsed" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="GridView.ColumnCollection" Value="{x:Null}">
<Setter TargetName="contentPresenter" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="Control.IsMouseOver" Value="true">
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Color="#FFE6E6E6" Opacity="0.75"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" >
<Setter.Value>
<SolidColorBrush Color="#FFA5C5D1" Opacity="0.75"/>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="Black"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
为什么这个样式会阻止DataTemplate被应用?
你试过不绑定ContentPresenter的Content
吗?默认情况下,没有它应该可以工作。绑定它(或者使用TemplateBinding)可能会破坏默认的ContentControl功能。
查看ListBoxItem
默认模板:msdn.microsoft.com/es-es/library/ms750821(v=vs.85).aspx
ContentPresenter
保持原样,剩下的是ContentControl逻辑。