[c#] Get the item doubleclick event of listview

What do I need to do in order to reference the double click event for a listview control?

This question is related to c# .net wpf wpf-controls

The answer is


for me, I do double click of ListView in this code section .

    this.listView.Activation = ItemActivation.TwoClick;

    this.listView.ItemActivate += ListView1_ItemActivate;

ItemActivate specify how user activate with items

When user do double click, ListView1_ItemActivate will be trigger. Property of ListView ItemActivate refers to access the collection of items selected.

    private void ListView1_ItemActivate(Object sender, EventArgs e)
    {

        foreach (ListViewItem item in listView.SelectedItems)
           //do something

    }

it works for me.


i see this subject is high on google, there is my simple and working sample :)

XAML:

    <ListView Name="MainTCList" HorizontalAlignment="Stretch" MinHeight="440" Height="Auto" Margin="10,10,5.115,4" VerticalAlignment="Stretch" MinWidth="500" Width="Auto" Grid.Column="0" MouseDoubleClick="MainTCList_MouseDoubleClick" IsSynchronizedWithCurrentItem="True">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="UserTID" DisplayMemberBinding="{Binding UserTID}" Width="80"/>
                <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" Width="410" />
            </GridView>
        </ListView.View>
    </ListView>

C#

    private void MainTCList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
            TC item = (TC)MainTCList.Items.CurrentItem;
            Wyswietlacz.Content = item.UserTID;  
    }

Wyswietlacz is a test Label to see item content :) I add here in this last line a method to Load Page with data from item.


I needed that as well. I found that on msdn:

http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.activation.aspx

I think this delegate is for that.


    private void positionsListView_DoubleClick(object sender, EventArgs e)
    {
        if (positionsListView.SelectedItems.Count == 1)
        {
            ListView.SelectedListViewItemCollection items = positionsListView.SelectedItems;

            ListViewItem lvItem = items[0];
            string what = lvItem.Text;

        }
    }

I don't yet have a large enough reputation score to add a comment where it would be most helpful, but this is in relation to those asking about a .Net 4.5 solution.

You can use the mouse X and Y co-ordinates and the ListView method GetItemAt to find the item which has been clicked on.

private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = myListView.GetItemAt(e.X, e.Y)
    // Do something here
}

Use the ListView.HitTest method

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;
        var clickedItem = senderList.HitTest(e.Location).Item;
        if (clickedItem != null)
        {
            //do something
        }            
    }

Or the old way

    private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        var senderList  = (ListView) sender;                        
        if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
        {
            //Do something
        }
    }

    public  bool IsInBound(Point location, Rectangle bound)
    {
        return (bound.Y <= location.Y && 
                bound.Y + bound.Height >= location.Y &&
                bound.X <= location.X && 
                bound.X + bound.Width >= location.X);
    }

You can get the ListView first, and then get the Selected ListViewItem. I have an example for ListBox, but ListView should be similar.

private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        ListBox box = sender as ListBox;
        if (box == null) {
            return;
        }
        MyInfo info = box.SelectedItem as MyInfo;
        if (info == null)
            return;
        /* your code here */
        }
        e.Handled = true;
    }

I found this on Microsoft Dev Center. It works correctly and ignores double-clicking in wrong places. As you see, the point is that an item gets selected before double-click event is triggered.

private void listView1_DoubleClick(object sender, EventArgs e)
{
    // user clicked an item of listview control
    if (listView1.SelectedItems.Count == 1)
    {
        //do what you need to do here            
    }
}

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/588b1053-8a8f-44ab-8b44-2e42062fb663


It's annoying, but the best way to do it is something like:

<DataTemplate Name="MyCoolDataTemplate">
    <Grid Loaded="HookLVIClicked" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}">
        <!-- your code here -->
    </Grid>
</DataTemplate>

Then in the code:

public void HookLVIClicked(object sender, RoutedEventArgs e) {
    var fe = (FrameworkElement)sender;
    var lvi = (ListViewItem)fe.Tag;
    lvi.MouseDoubleClick += MyMouseDoubleClickHandler;
} 

Either use the MouseDoubleClick event, and also, all the MouseClick events have a click count in the eventargs variable 'e'. So if e.ClickCount == 2, then doubleclicked.


<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <EventSetter Event="MouseDoubleClick" Handler="listViewItem_MouseDoubleClick" />
    </Style>
</ListView.ItemContainerStyle>

The only difficulty then is if you are interested in the underlying object the listviewitem maps to e.g.

private void listViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ListViewItem item = sender as ListViewItem;
    object obj = item.Content;
}

Was having a similar issue with a ListBox wanting to open a window (Different View) with the SelectedItem as the context (in my case, so I can edit it).

The three options I've found are: 1. Code Behind 2. Using Attached Behaviors 3. Using Blend's i:Interaction and EventToCommand using MVVM-Light.

I went with the 3rd option, and it looks something along these lines:

<ListBox x:Name="You_Need_This_Name"  
ItemsSource="{Binding Your_Collection_Name_Here}"
SelectedItem="{Binding Your_Property_Name_Here, UpdateSourceTrigger=PropertyChanged}"
... rest of your needed stuff here ...
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
    <Command:EventToCommand Command="{Binding Your_Command_Name_Here}" 
        CommandParameter="{Binding ElementName=You_Need_This_Name,Path=SelectedItem}"     />
    </i:EventTrigger>
</i:Interaction.Triggers>

That's about it ... when you double click on the item you want, your method on the ViewModel will be called with the SelectedItem as parameter, and you can do whatever you want there :)


The sender is of type ListView not ListViewItem.

    private void listViewTriggers_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        ListView triggerView = sender as ListView;
        if (triggerView != null)
        {
            btnEditTrigger_Click(null, null);
        }
    }

Here is how to get the selected object and object matching code for the double clicked listview item in a WPF listview:

/// <summary>
/// Get the object from the selected listview item.
/// </summary>
/// <param name="LV"></param>
/// <param name="originalSource"></param>
/// <returns></returns>
private object GetListViewItemObject(ListView LV, object originalSource)
{
    DependencyObject dep = (DependencyObject)originalSource;
    while ((dep != null) && !(dep.GetType() == typeof(ListViewItem)))
    {
        dep = VisualTreeHelper.GetParent(dep);
    }
    if (dep == null)
        return null;
    object obj = (Object)LV.ItemContainerGenerator.ItemFromContainer(dep);
    return obj;
}

private void lvFiles_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    object obj = GetListViewItemObject(lvFiles, e.OriginalSource);
    if (obj.GetType() == typeof(MyObject))
    {
        MyObject MyObject = (MyObject)obj;
        // Add the rest of your logic here.
    }
}       

In the ListBox DoubleClick event get the selecteditem(s) member of the listbox, and there you are.

void ListBox1DoubleClick(object sender, EventArgs e)
    {
        MessageBox.Show(string.Format("SelectedItem:\n{0}",listBox1.SelectedItem.ToString()));
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to wpf

Error: the entity type requires a primary key Reportviewer tool missing in visual studio 2017 RC Pass command parameter to method in ViewModel in WPF? Calling async method on button click Setting DataContext in XAML in WPF How to resolve this System.IO.FileNotFoundException System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll? Binding an Image in WPF MVVM How to bind DataTable to Datagrid Setting cursor at the end of any text of a textbox

Examples related to wpf-controls

How to create/make rounded corner buttons in WPF? Formatting text in a TextBlock How do I make XAML DataGridColumns fill the entire DataGrid? What is The difference between ListBox and ListView How to display the current time and date in C# Simple (I think) Horizontal Line in WPF? WPF: ItemsControl with scrollbar (ScrollViewer) Align items in a stack panel? Wpf control size to content? How to bind to a PasswordBox in MVVM