如何为每个ListBoxItem设置工具提示

时间:2012-09-14 19:29:19

标签: wpf listbox tooltip itemtemplate

我有一个ListBox控件;如何使用以下代码为每个ToolTip设置ListBoxItem

<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>

2 个答案:

答案 0 :(得分:1)

尝试这样的事情

<ListBox Width="400" Margin="10" 
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=TaskName}" 
                       ToolTipService.ToolTip="{Binding Path=TheTooltipText}"/>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>

当然,使用您的绑定源调整ItemsSource绑定,并使用您实际想要显示的列表中的对象的任何公共属性来绑定Path部分。

答案 1 :(得分:1)

您可以为ListBoxItem创建样式。所以有些东西:

<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>