views:

4095

answers:

4

I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.

I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.

I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.

+4  A: 

There are two main problems to solve to solve this problem:

  1. Determine which item is being hovered over
  2. Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item.

The first problem is rather simple to solve. By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over:

    private ITypeOfObjectsBoundToListBox DetermineHoveredItem()
    {
        Point screenPosition = ListBox.MousePosition;
        Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition);

        int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition);
        if (hoveredIndex != -1)
            return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox;
        else
            return null;        
    }

Then use the returned value to set the tool-tip as needed.

The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back.

You can get around this by wrapping the TrackMouseEvent Win32API call. In the following code, the ResetMouseHover method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired.

public static class MouseInput
{
    // TME_HOVER
    // The caller wants hover notification. Notification is delivered as a 
    // WM_MOUSEHOVER message.  If the caller requests hover tracking while 
    // hover tracking is already active, the hover timer will be reset.

    private const int TME_HOVER = 0x1;

    private struct TRACKMOUSEEVENT
    {
        // Size of the structure - calculated in the constructor
        public int cbSize;

        // value that we'll set to specify we want to start over Mouse Hover and get
        // notification when the hover has happened
        public int dwFlags;

        // Handle to what's interested in the event
        public IntPtr hwndTrack;

        // How long it takes for a hover to occur
        public int dwHoverTime;

        // Setting things up specifically for a simple reset
        public TRACKMOUSEEVENT(IntPtr hWnd)
        {
            this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));
            this.hwndTrack = hWnd;
            this.dwHoverTime = SystemInformation.MouseHoverTime;
            this.dwFlags = TME_HOVER;
        }

    }

    // Declaration of the Win32API function
    [DllImport("user32")]
    private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);

    public static void ResetMouseHover(IntPtr windowTrackingMouseHandle)
    {
        // Set up the parameter collection for the API call so that the appropriate
        // control fires the event
        TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle);

        // The actual API call
        TrackMouseEvent(ref parameterBag);
    }

}

With the wrapper in place, you can simply call ResetMouseHover(listBox.Handle) at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds.

I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done. Any improvements are more than welcome.

Michael Lang
+1  A: 

I think the best option, since your databinding your listbox to objects, would be to use a datatemplate. So you could do something like this:

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

(Sorry about the indentation, can't seem to get it right...) Of course you'd replace the ItemsSource binding with whatever your binding source is, and the binding Path parts with whatever public property of the objects in the list you actually want to display. The following link has more details: http://msdn.microsoft.com/en-us/library/ms742521.aspx

Alex
A: 

Using title attribute, we can set tool tip for each list items in a list box.

Loop this for all the items in a list box.

ListItem li = new ListItem("text","key"); li.Attributes.Add("title","tool tip text");

Hope this helps.

A: 

Here is a Style that creates a group of RadioButtons by using a ListBox. All is bound for MVVM-ing. MyClass contains two String properties: MyName and MyToolTip. This will display the list of RadioButtons including proper ToolTip-ing. Of interest to this thread is the Setter for ToolTip near bottom making this an all Xaml solution.

Example usage:

ListBox Style="{StaticResource radioListBox}" ItemsSource="{Binding MyClass}" SelectedValue="{Binding SelectedMyClass}"/>

Style:

    <Style x:Key="radioListBox" TargetType="ListBox" BasedOn="{StaticResource {x:Type ListBox}}">
    <Setter Property="BorderThickness" Value="0" />
    <Setter Property="Margin" Value="5" />
    <Setter Property="Background" Value="{x:Null}" />
    <Setter Property="ItemContainerStyle">
        <Setter.Value>
            <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Grid Background="Transparent">
                                <RadioButton Focusable="False" IsHitTestVisible="False" IsChecked="{TemplateBinding IsSelected}" Content="{Binding MyName}"/>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="ToolTip" Value="{Binding MyToolTip}" />
            </Style>
        </Setter.Value>
    </Setter>
</Style>
BSalita