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

2 c# wpf

我在WPF中有一个列表框

<ListBox Name="lstName" DisplayMemberPath ="ListName" ToolTip="{Binding Path=ListName}" />
Run Code Online (Sandbox Code Playgroud)

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

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

该实体如下

public class ItemList
{
  public string ListName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

绑定发生在下面

this.lstName.ItemsSource = GetData(); // Assume that the data is coming properly
Run Code Online (Sandbox Code Playgroud)

Qua*_*ter 8

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

<ListBox Name="lstName" DisplayMemberPath="ListName">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="ToolTip" Value="{Binding ListName}"/>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

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

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