Search code examples
wpflistboxtooltipitemtemplate

How to set a ToolTip for each ListBoxItem


I have a ListBox control; how would I set the ToolTip for each ListBoxItem using the code below.

<ListBox Name="FillSelections" 
         VerticalContentAlignment="Stretch"
         Margin="1, 3, 1, 3"
         IsEnabled="True" 
         Grid.Column="0" 
         Background="Transparent"
         HorizontalContentAlignment="Center"
         SelectedItem="{Binding SelectedColor}"
         SelectionMode="Single"
         Style="{StaticResource HorizontalListBoxStyle}"
         ItemsSource="{Binding FillColors}"
         ItemTemplate="{StaticResource ColorsItemTemplate}">
</ListBox>

<DataTemplate x:Key="ColorsItemTemplate">
    <Border Width="20" 
            Height="16"
            BorderBrush="Black"
            BorderThickness="1">
        <Border.Background>
            <SolidColorBrush Color="{Binding}" />
        </Border.Background>
        <Path Stroke="Red" 
              StrokeThickness="3"
              x:Name="abc"
              Visibility="Hidden">
            <Path.Data>
                <LineGeometry StartPoint="0,16" EndPoint="20,0"/>
            </Path.Data>
        </Path>
    </Border>
    <DataTemplate.Triggers>
        <DataTrigger Binding="{Binding}" Value="#00FFFFFF">
            <Setter TargetName="abc" Property="Visibility" Value="Visible"/>
        </DataTrigger>
    </DataTemplate.Triggers>
</DataTemplate>

Solution

  • You could create a style for ListBoxItem. So something along the lines of:

    <Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="ToolTip">
                    <Setter.Value>
                        <ToolTip>
                            <TextBlock>Hello</TextBlock>
                        </ToolTip>
                    </Setter.Value>
                </Setter>
            </Style>
       </Window.Resources>
        <Grid>
            <ListBox>
                <ListBoxItem>
                    <TextBlock Text="Hello" />
                </ListBoxItem>
            </ListBox>
        </Grid>
    </Window>