views:

29

answers:

1

I have a ListBox container data bound and templatized as so:

    <ListBox x:Name="ListBox" 
             ItemsSource="{Binding Source={StaticResource List}}"
             ItemTemplate="{StaticResource ListTemplate}">
    </ListBox>

Within my ListTemplate resource, I define a Grid which contains a few child elements. I have setup a click event handler on one of child elements. The event hander is not row-specific, and I need a (best practice) way of identifying which row in the ListBox the event fired upon.

From my data source, I have an unique ID which corresponds to the row. I do not currently expose this ID in the data binding, though could. Ideally I would like the event handler to be able to identify the ID of the row the event was fired upon.

+1  A: 

It would be great if you can show us the definition of your grid in order to get a better picture of your problem.

Since my Grid's DataContext has all the data I need, what I do is the following (I try to use commands when possible, but also works with event handlers)

    private void NotificationLinkClick(object sender, RoutedEventArgs e)
    {
        var myDataObject = ((Hyperlink)sender).DataContext as MyDataObject;
        DoSomeWork(myDataObject);
    }

I have a Hyperlink for each row in my grid. In order to know which one was selected, in the event handler I get the DataContext and then I cast it to my underlying object. Once I got the "row", I do what I need to do.

Also, as Anthony suggest, we can make the thing more generic

    private void NotificationLinkClick(object sender, RoutedEventArgs e)
    {
        var myDataObject = ((FrameworkElement)sender)
                                             .DataContext as MyDataObject;
        DoSomeWork(myDataObject);
    }

I'm pretty sure there's a better/cleaner way to do it, but this works. HTH

Markust
+1, and no I don't think that other approaches are necessarily better or cleaner. Perhaps if a MVVM framework were use of a Command might be better but your approach is by far simplest. (I'd perhaps change `Hyperlink` to the largest type that has the `DataContext` property rather than limit the code to only work with Hyperlinks).
AnthonyWJones
Edited, thanks for the advice.
Markust