开发者

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 c开发者_如何学编程lick 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜