Mike Knoop
Mike Knoop

Reputation: 506

How to Identify Caller for Template Events

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.

Upvotes: 1

Views: 184

Answers (1)

Marcote
Marcote

Reputation: 3105

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

Upvotes: 1

Related Questions