views:

882

answers:

1

I have a different style for the items in my listbox on MouseOver which gives a slight zoom effect. This works nicely, but since the ZIndex is set in the order items are added to the ListBox, the zoomed item will be drawn behind the next item. I would like to set it so that the zoomed item is on top.

I've tried creating a MouseOver eventhandler, and setting the ZIndexProperty like this

    private void ListItem_MouseEnter(object sender, MouseEventArgs e)
    {
        var grid = sender as Grid;            
        grid.SetValue(Canvas.ZIndexProperty, 5);
    }

This doesn't work, and if I check the ZIndex without setting it at all, I always get 0 so it's like I'm not looking at the correct value. How can I modify the correct ZIndexProperty?

+1  A: 

You don't include the relevant Xaml so it's hard for me to tell what event ListItem_MouseEnter is the handler for. If it's a handler for a ListBoxItem's MouseEnter event the sender will not be a Grid.

To change the ZIndex of a ListBoxItem on MouseOver the Xaml and code below will work:

Page.xaml

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="ListBox1">
            <ListBoxItem Content="Test 1" MouseEnter="ListBoxItem_MouseEnter" />
            <ListBoxItem Content="Test 2" MouseEnter="ListBoxItem_MouseEnter" />
            <ListBoxItem Content="Test 3" MouseEnter="ListBoxItem_MouseEnter" />
            <ListBoxItem Content="Test 4" MouseEnter="ListBoxItem_MouseEnter" />
        </ListBox>
    </Grid>
</UserControl>

Page.xaml.cs:

using System;
using System.Windows.Controls;
using System.Windows.Input;

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

        private void ListBoxItem_MouseEnter(object sender, MouseEventArgs e)
        {
            ListBoxItem listBoxItem = (ListBoxItem)sender;

            listBoxItem.SetValue(Canvas.ZIndexProperty, 5);
        }
    }
}

Notice the event handler is for each ListBoxItem's MouseEnter event meaning the sender is a ListBoxItem.

The ListBoxItem_MouseEnter method changes the Zindex to 5 on MouseEnter, verified using Silverlight Spy.

Peter McGrattan