Sign in to follow this  
beun

[.net] [WPF] Events from ListView (GridView)'s data binded items

Recommended Posts

Hello, I'm using WPF and C# and one of my controls is a ListView. The view mode for the ListView is GridView, and the ListView is populated by DataContext/ItemsSource/data binding. I want to show a window with details about an item if that item is doubleclicked. First I tried to add a MouseDoubleClick event handler to the ListView. I read ListView.SelectedIndex, and I show a window with details about that item. The problem is: when I doubleclick on the ListView but not on an actual item (near the red dot), the doubleclick is processed too, and I don't know whether an actual item is under the mouse or not (because the item isn't deselected when you click somewhere else). ListView I was also surprised by the result of this:
MessageBox.Show(listView.Items[0].GetType().ToString());

which is the actual type of the binded data (Value), while I expected it to be ListViewItem. So I can't add an event handler this way. So I wonder if there's a way to add an event handler to the actual items, instead of adding it to the ListView. I hope someone can help me here. Thanks in advance.

Share this post


Link to post
Share on other sites
You don't need code-behind to do this, you can do it all via binding, if you don't really need to launch another actual window. What you're trying to do is a 'master-detail view', and you can find plenty of detailed examples via Google if you add that term to your search terms.

Briefly, however, the list view is the master view and you want to bind some other control to it's SelectedItem property. You can do this most directly (although this is not necessarily the best implementation) like:

<ListView x:Name="master">
...
</ListView>
<TextBlock Text="{Binding SelectedItem.SomePropertyHere,ElementName="master"/>

The text block will then show the SomePropertyHere property of the selected item in the list view. You'll probably actually want to bind the data context of some content presenter control to the selected item itself and use data template selection to pick up the XAML to display the detail view, but that's a more complex example.

If you really do need to trap the double click, you'll have to set it for the list view and do element probing. You can use a style setter to attach the event handler to just ListViewItems, but that will still fire on the header objects, so you'll still need element probing anyhow to discover which actual item was hit.

You may want to consider switching to the DataGrid control in the WPF Toolkit which has better support for this sort of thing.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this