tags:

views:

91

answers:

1

Hi

I am trying to determine which row (RowDefinition) my mouse is over within a WPF grid.

I have tried adding the MouseEnter event to the RowDefinition but the event doesn't fire, the Event does fire on the Grid itself but that doesn't help as I need the name of the row the mouse is currently over.

Thanks in advance.

+1  A: 

Have your handler on each element, not on the grid itself. E.g. if you have TextBlocks there you can set handler using style:

<Grid Name="_grid">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <EventSetter Event="MouseEnter" Handler="EventSetter_OnHandler" />
        </Style>
    </Grid.Resources>
        <TextBlock>a</TextBlock>
        <TextBlock Grid.Row="1">b</TextBlock>
        <TextBlock Grid.Row="2">c</TextBlock>
</Grid>

Then within handler you know the element from MouseEventArgs.Source. Do GetValue(Grid.RowProperty) if you need to find out row number and if you really need RowDefinition, get it from Grid.RowDefinitions:

private void EventSetter_OnHandler(object sender, MouseEventArgs e)
{
    var element = (FrameworkElement) e.Source;
    var rowNumber = (int) element.GetValue(Grid.RowProperty);
    RowDefinition rowDefinition = _grid.RowDefinitions[rowNumber];
    e.Handled = true;
}
repka
I'm a bit worried about adding UI Elements to the rows because there could be 72 rows per grid and 4 to 7 grids so it could get up to 500+ rows. I'm worried about the efficiency and that's why I am looking to the grid to provide a event.
Organ Grinding Monkey
The good thing about WPF is that routed events, just as properties, are not initialized/stored per instance. The event will be stored in style object and style object will be "projected" onto each row. Mouse enter event happens whether its handled or not on each component anyway.With lots of rows you should look into using virtual panels though or something like DataGrid (it uses virtual panel within itself). You don't want to create 500 instances of whatever elements you'll have for each row.
repka