我想在listBoxItem中添加工具提示,但是当有displayMemberPath时它会启动问题.错误信息说:无法同时设置displayMemberPath和ItemTemplate.当我删除displayMemberPath时,每个列表项中的工具提示都有效.但我不想删除displayMemember因为我需要它.如何解决这个问题呢?
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}" displayMemberPath="Toys" MouseDoubleClick="lstToys_MouseDoubleClick"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" ToolTip="Here is a tooltip"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
解决方法
displayMemberPath实际上是单个属性的模板,显示在TextBlock中.如果你设置:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}" displayMemberPath="Toys"> </ListBox>
它相当于:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Toys}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
您只需删除displayMemberPath路径并使用DataTemplate的Binding中的值:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Toys}" ToolTip="Here is a tooltip!"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
编辑
如果要设置工具提示但保留displayMemberPath,可以在ItemContainerStyle中执行:
<ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}" displayMemberPath="Toys"> <ListBox.ItemContainerStyle> <Style targettype="ListBoxItem"> <Setter Property="ToolTip" Value="Here's a tooltip!"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
我建议不要这样做.请记住,使用displayMemberPath可以阻止数据模板中的任何复杂绑定.