MouseOver event for ListBoxItems
Last post 04-24-2008 11:12 PM by sladapter. 3 replies.
Sort Posts:
04-24-2008 5:44 AM
MouseOver event for ListBoxItems

ListBox has an event for SelectionChanged but I can't wait for the user to "click" an item I need to detect when the user puts the mouse over an item.  More specifically I need to know which item has the mouse over it.  This context determines the action I take.

 

Here is the scenario... 

I've got an application that needs to perform an action when the Mouse goes over one of the items in a list box.  For example imagine the following list


item1: on mouse over start a video

item2: on mouse over display some UserControl

item3: on mouse over email billgates

 


Originally I figured I could try listening to the MouseOver event on the ListBox and do some hitTesting to figure out which item is highlight.  However I cannot see anything that lets me into the children elements of the ListBox to perform the hitTesting.  I know that there are StoryBoards that get triggered in the ControlTemplate but these are purely for animations and cannot trigger C# client code (can they?).

 

Suggestions?  Ideas?

 

Thanks,

Justin
 

coughlinj

Loading...
Joined on 03-07-2008
Vancouver
Posts 94
04-24-2008 6:25 AM
Marked as Answer
Re: MouseOver event for ListBoxItems

One idea is to create a UserControl for the DataTemplate of your ListBox.  Do the mouseover in the UserControl and create yoru DataTemplate using the new UserControl for every item.

(If this has answered your question, "Mark as Answer")

Shawn Wildermuth
C# MVP, MCSD, Speaker and Author

Silverlight 2 Workshop
October 22-24, 2008 - Atlanta, GA
November 3-5, 2008 - San Diego, CA
http://silverlight-tour.com

swildermuth

Loading...
Joined on 10-13-2003
Atlanta, GA
Posts 1,229
04-24-2008 6:11 PM
Re: MouseOver event for ListBoxItems

Ok that is a fantastic idea!

BUT...  for some reason I can't get the DataTemplate to accept a UserControl that I create.  On the bright side you triggered me to just add a MouseEnter event to the Grid element that is the base of my DataTemplate and that solves the problem with one little caviot.  The Grid does not expand to the full width of the list box.  Instead it only expands to the width of the items content.  See http://silverlight.net/forums/p/14865/49109.aspx#49109 for a better description of my remaining problem.

 As for using a UserControl approach I'm interested in pursuing that route still as it seems like it offers other benefits.  I've seperated the code into a very small project described here...

Page.xaml 

 <UserControl x:Class="MouseOverListItems.Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:MouseOverListItems"
    Width="400" Height="300">

    <StackPanel>
        <!-- Proof that the itemUserControl is valid -->
        <src:itemUserControl />

        <!-- Proof that the DataTemplate / List Box is valid -->
        <ListBox x:Name="listBox">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="hello" />
                        </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

        <!-- Put it together -->
        <ListBox x:Name="listBox2">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <!--src:itemUserControl /-->
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
</UserControl>
 

Page.xaml.cs

using System.Collections.Generic;
using System.Windows.Controls;

namespace MouseOverListItems
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();

            listBox.ItemsSource = new List<string> {"a", "b", "c"};
            listBox2.ItemsSource = new List<string> { "a", "b", "c" };
        }
    }
}

ItemUserControl.xaml... 

<UserControl x:Class="MouseOverListItems.itemUserControl"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid Background="White">
        <TextBlock Text="an item" />
    </Grid>
</UserControl>

 

Notice that if you uncomment the line <!--src:itemUserControl /--> in the second listbox the browser hangs???

 

Thanks for your help.  It is very very appreciated.  I'm finding this user forum an excellent resource. 

 

coughlinj

Loading...
Joined on 03-07-2008
Vancouver
Posts 94
04-24-2008 11:12 PM
Marked as Answer
Re: MouseOver event for ListBoxItems

You can try the following code: it use mouseEnter event to trigger menu action: 

Page.XAML:

<UserControl x:Class="Page"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    
      >
    <Grid>     
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>


        <!-- Menu -->
        <ListBox x:Name="MenuList">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border x:Name="Menu" HorizontalAlignment="Stretch" MouseEnter="Menu_MouseEnter" Loaded="Menu_Loaded" Background="Transparent" Cursor="Hand">
                        <TextBlock Text="{Binding Text}"/>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>


       <!-- Content Container -->
        <Grid Grid.Column="1" Margin="5,0,5,0" ShowGridLines="False" Background="White">           
            <Border BorderThickness="1" BorderBrush="#ccc">
                <Grid x:Name="ContentContainer" Margin="5">
                    <TextBlock>Control Detail</TextBlock>
                </Grid>
            </Border>           
        </Grid>
    </Grid>
</UserControl>

 

Page.XAML.cs:

namespace YourNameSpace
{
    public partial class Page: UserControl
    {       
        public Page()
        {
            InitializeComponent();           
           
            List<MenuData> list = new List<MenuData>();

            list.Add(new MenuData { Text = "Menu Item 1", Url = "http://silverlight.net/Samples/2b1/SilverlightControls/run/default.html" });
            list.Add(new MenuData { Text = "Menu Item 2", ControlType = typeof([UserControl you want to put to the page content area]).FullName });
            list.Add(new MenuData { Text = "Menu Item 3" });

            MenuList.ItemsSource = list;
        }

     
        private void Menu_Loaded(object sender, RoutedEventArgs e)
        {
           //This is a workaround for a bug in ListBox in SL2 beta, The ListItem won't Stretch to the full length.

            FrameworkElement g = sender as FrameworkElement;
            g.Width = MenuList.ActualWidth;
        }       

        private void Menu_MouseEnter(object sender, MouseEventArgs e)
        {          
            FrameworkElement g = sender as FrameworkElement;
            MenuData m = g.DataContext as MenuData;
            if (m != null)
            {
                if (m.ControlType != null)
                {
                    UIElement o = this.GetType().Assembly.CreateInstance(m.ControlType) as UIElement;                   
                    ContentContainer.Children.RemoveAt(0);
                    ContentContainer.Children.Add(o);
                }
                else if (m.Url != null)
                {
                    HtmlPage.Window.Navigate(new Uri(m.Url), "_blank");
                }
                else
                {

//do something you want.
                 }
            }
        }                              
    }
}

ManuData.cs - just the code, no XAML . This is the Data object for holding MenuData

public class MenuData
    {
        public string MenuText { get; set; }
        public string ControlType { get; set; }
        public string Url { get; set; }
    }

sladapter
Software Engineer
Aprimo, Inc

Please remember to mark the replies as answers if they answered your question

sladapter

Loading...
Joined on 03-05-2008
Indiana, US
Posts 2,489
Page view counter