19 November 2014

MVVM: Binding ListBox item double click event to a command

With intention of having 'no code' in code behind file, we often invest lot of time in finding how to invoke a command in your ViewModel whenever a UIElement raises an event. I certainly invested couple of hours googling.. binging for readymade answers. I couldn't find a satisfactory answers (may be I am poor in using right keywords ). But, with help of couple of posts in sites like StackOverflow & MSDN, I arrived at this very simple approach.

Below is my ViewModel which has a collection called Cities which I will be displaying in a ListBox in my View. My ViewModel has a command called ItemSelectedCommand which should be incoked when user double clicks on city.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// <summary>
/// ViewModel for CityView
/// </summary>
public class CityViewModel : ViewModelBase
{
    /// <summary>
    /// Command that responds item double click event.
    /// </summary>
    public DelegateCommand ItemSelectedCommand { get; private set; }

    /// <summary>
    /// Gets or sets the selected city.
    /// </summary>
    public string SelectedCity { get; set; }

    /// <summary>
    /// Gets the list of cities.
    /// </summary>
    public List<string> Cities { get; private set; }

    /// <summary>
    /// Initializes new instance of <see cref="CityViewModel"/> class.
    /// </summary>
    public CityViewModel()
    {
        ItemSelectedCommand = new DelegateCommand(OnItemSelected);
        Cities = new List<string>() { "Bangalore", "New York", "Sydney", "London", "Washington" };
    }

    /// <summary>
    /// This method is executed when user double clicks on a city.
    /// </summary>
    /// <param name="sender">Unsed Parameter.</param>
    private void OnItemSelected(object sender)
    {            
        //Do the processing you need
    }
}


And here is the XAML

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<ListBox HorizontalAlignment="Center" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}">
                <TextBlock.InputBindings>
                    <MouseBinding Gesture="LeftDoubleClick"                                           
                                  Command="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=DataContext.ItemSelectedCommand}"/>
                </TextBlock.InputBindings>
            </TextBlock>
        </DataTemplate>
    </ListBox.ItemTemplate>                  
</ListBox>


I hope there is no need to explain the code and I hope you enjoyed reading this :)

14 comments:

  1. your concept is really good and it is really nice and very much interesting, thus it is very well done as well as it is good to see the interesting information.

    Android Training in Chennai

    ReplyDelete
  2. Hi,
    I am still a bit of a noob in this, but do you think you can help? I do not understand how you get to have an object sender as parameter in your OnItemSelected method.
    All I manage is to have a method without a parameter. :(
    Where do you get your DelegateCommand class from? Maybe that is my issue.
    Thank you for your time.

    ReplyDelete
  3. I have been surfing the internet for the past two hours and I have not come across such an interesting and intriguing site. It has helped me learn new programming techniques thus increasing my general programming knowledge. I will be visiting this site occasionally to read more articles as I look for online writers who help with Correcting Errors in a Case Study.

    ReplyDelete
  4. Great information...Your post the very informative i have learned some information about your blog thank you for Sharing the great information....
    PMP Training | CSM Trainning

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Great blog explanation informative

    Sanjary Academy provide pressure vessel design,quality management system course, piping design course, qa/qc course and document controller course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  8. Hi there colleagues, good paragraph and good urging commented here, I am genuinely enjoying by these. Barkatullah University BA Part 3 Result

    ReplyDelete
  9. Useful post Thanks for sharing it that’s truly valuable knowledge about similar topic. Amazing. Have a more successful day. Amazing write-up always finds something interesting. .
    Personality Development Classes

    ReplyDelete
  10. Thanks for sharing Nice content with us. For business growth and promote, Check; Digital Marketing Training in Noida

    ReplyDelete