Search code examples
c#wpfdata-binding

DoubleClick on my ListBox item is not being fired


I am implementing a listbox using MVVM approach and I'm having an issue where my double click command is not being triggered. When I launch my application I see my ListBox populated via binding just fine. But when I double click on an item nothing happens. Is there something I'm missing? Many thanks in advance.

Here is how I have my UserControl (xaml) set up

    <ListBox 
        x:Name="Files" 
        ItemsSource="{Binding FileCollection, Mode=TwoWay}"
        SelectedItem="{Binding Filename, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}">                                    
                    <TextBlock.InputBindings>
                        <MouseBinding  
                         Gesture="LeftDoubleClick" 
                         Command="{Binding EditFileCommand}"/>
                    </TextBlock.InputBindings>
               </TextBlock>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

This is how I am setting up my command object in my View Model:

        //..using system.windows.input for ICommand
        private ICommand editFileCommand = null;
        public ICommand EditFileCommand
        {
            get
            {
                //RelayCommand comes from GalaSoft.MvvmLight.Command
                return editFileCommand ?? new RelayCommand(EditFile); 
            }
        }

        private void EditFile()
        {
            MessageBox.Show("Double Click!");
        }

Solution

  • This is almost similar to RelayCommand, you can use it like this:

    Declare in your ViewModel:

    public RelayCommand EditFileCommand { get; set; }
    

    Then, you need to initialize it:

    EditFileCommand = new RelayCommand(EditFile);
    

    The XAML remains equal:

    <ListBox 
            x:Name="Files" 
            ItemsSource="{Binding FileCollection, Mode=TwoWay}"
            SelectedItem="{Binding Filename, Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}">                                    
                        <TextBlock.InputBindings>
                            <MouseBinding  
                             Gesture="LeftDoubleClick" 
                             Command="{Binding EditFileCommand}"/>
                        </TextBlock.InputBindings>
                   </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>