C # wpf - cannot set both DisplayMemberPath and ItemTemplate

I want to add a tooltip to listboxItem, but it triggers a problem when there is DisplayMemberPath. The error message indicated: both DisplayMemberPath and ItemTemplate cannot be set. When I removed DisplayMemberPath, the tooltip in each list item works. But I do not want to remove DisplayMemember, because I need it. How to solve this problem?

<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> 
+6
source share
1 answer

DisplayMemberPath is essentially a template for a single property shown in a TextBlock . If you installed:

 <ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}" DisplayMemberPath="Toys"> </ListBox> 

This is equivalent to:

 <ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Toys}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

You can simply remove the DisplayMemberPath path and use the value in the 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> 

Edit

If you want to set ToolTip , but save DisplayMemberPath , you can do this on ItemContainerStyle :

 <ListBox x:Name="lstToys" Style="{DynamicResource ListBoxStyle1}" ItemsSource="{Binding Strings}" DisplayMemberPath="Toys"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="ToolTip" Value="Here a tooltip!"/> </Style> </ListBox.ItemContainerStyle> </ListBox> 

I would advise doing this. Remember that using DisplayMemberPath stops you from any complex binding in your data template.

+13
source

Source: https://habr.com/ru/post/951879/


All Articles