如何通过XAML设置LISTBOX工具提示

时间:2010-07-30 03:20:57

标签: c# wpf

我在WPF中有一个列表框,在

下面
<ListBox Name="lstName" DisplayMemberPath ="ListName" ToolTip="{Binding Path=ListName}" />

我的要求是,我在列表框中显示的项目也应出现在工具提示中。即,如果项目是“Item1”,“Item2”等,则当用户通过鼠标指向(悬停)“Item1”时,工具提示应显示“Item1”。其他人也一样

所以我的DisplayMemberPath被设置为我应该显示的属性(并且它正常运行)。但是,工具提示根本不会出现。

该实体位于

之下
public class ItemList
{
  public string ListName { get; set; }
}

绑定发生在

之下
this.lstName.ItemsSource = GetData(); // Assume that the data is coming properly

1 个答案:

答案 0 :(得分:8)

不是在ListBox上设置ToolTip属性,而是通过应用样式在ListBoxItems上设置它:

<ListBox Name="lstName" DisplayMemberPath="ListName">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ToolTip" Value="{Binding ListName}"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

这样,每个ListBoxItem都有自己的工具提示,显示该项的值。

由于您直接在ListBox上设置ItemsSource,您可能没有设置DataContext,因此Binding将无法在那里工作。如果您将DataContext设置为列表,那么无论鼠标在ListBox上的哪个位置,该绑定都会将当前选定的项目显示为工具提示。

相关问题