Question

I've found a solution for having a tooltip follow the cursor / mouse.

This works very well for me. However, I can't seem to figure out how to apply this method to a ListViewItem. Here is an example of one of my listview's XAML:

<ListView Name="lvBoxes" FontSize="9" Margin="0,0,0,5" Width="125" 
                ItemsSource="{Binding}" 
                SelectionChanged="lvBoxes_SelectionChanged" 
                MouseLeftButtonUp="lvBoxes_MouseLeftButtonUp">
    <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                    <EventSetter Event="MouseMove" Handler="lvBoxesItem_MouseMove" />
                    <Style.Triggers>
                            <DataTrigger Binding="{Binding Verified}" Value="True">
                                    <Setter Property="Background" Value="LightGreen" />
                            </DataTrigger>
                    </Style.Triggers>
            </Style>
    </ListView.ItemContainerStyle>
    <ListView.View>
            <GridView>
                    <GridViewColumn DisplayMemberBinding="{Binding Boxnum}" Header="BOX#" Width="50" />
                    <GridViewColumn DisplayMemberBinding="{Binding Qty}" Header="QTY" Width="50" />
            </GridView>
    </ListView.View>

I've tried adding <Setter x:Name="ttBox" Property="ToolTip" Value="A Tooltip" /> to the <Style>, but I'm unable to reference (in this example) ttBox in the code behind.

Was it helpful?

Solution

The discussion I originally linked to had me trying to access the ListViewItem.ToolTip in code behind as follows (assuming I had included <Setter x:Name="ttBox" Property="ToolTip" Value="A Tooltip" /> in my originally posted XAML <style> section):

private void lvBoxesItem_MouseMove(object sender, MouseEventArgs e)
{
    ttBox.Placement = System.Windows.Controls.Primitives.PlacementMode.Relative;
    ttBox.HorizontalOffset = e.GetPosition((IInputElement)sender).X + 10;
    ttBox.VerticalOffset = e.GetPosition((IInputElement)sender).Y + 10;    
}

I've found that while I wasn't able to access the ToolTip by x:Name in code behind, I was able to modify my code behind as follows to achieve the effect I was looking for (this requires that you don't set the ToolTip property in XAML):

ToolTip tt = new ToolTip(); // Initialized with the Window

private void lvBoxesItem_MouseMove(object sender, MouseEventArgs e)
{
    ListViewItem lvItem = sender as ListViewItem;
    lvItem.ToolTip = tt;
    tt.Content = "Sample ToolTip Text";
    tt.Placement = System.Windows.Controls.Primitives.PlacementMode.Relative;
    tt.HorizontalOffset = e.GetPosition((IInputElement)sender).X + 10;
    tt.VerticalOffset = e.GetPosition((IInputElement)sender).Y + 10;    
}

I should note, however, that this is only effective if you don't need/want to bind data directly to your ToolTip, which, in my case, isn't necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top