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 :)

15 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. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post. Your articles really impressed for me,because of all information so nice.

    Dataware Housing Training in Chennai

    ReplyDelete
  3. 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
  4. 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
  5. 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
  6. Really it was an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing..
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  7. Very nice publish! Thanks for the write about. It was very helpful and beneficial.
    Best web development services in bangalore
    BEST web designers in bangalore

    ReplyDelete
  8. thanks for sharing the information.
    Indian Cyber Army’s most awaited internship is live now. Summer Internship 2018 on “ Ethical hacking” and book your seats before it runs out.Candidates have to get themselves registered to be a part of this Internship program. Here internship will give you on-the-job experience, help you learn whether you and Cyber security industry are a good match and can provide you with valuable connections and references. Here interns are usually exposed to a wide variety of tasks and responsibilities which allows the intern to showcase their strengths by working on projects for various managers that work on different parts of Indian Cyber Army. Becoming a high performing intern is a fantastic way to improve your employment prospects. This internship can be a great way to get your foot in the door of success with a prestigious or desirable Organization.As career in ethical hacking is most in demand.

    ReplyDelete
  9. thanks for sharing the more valuable information.
    Indian Cyber Army credibility in Ethical hacking training & Cybercrime investigation training is acknowledged across nation as we offer hands on practical knowledge and full assistance with basic as well as advanced level ethical hacking & cybercrime investigation courses. The training is conducted by subject specialist corporate professionals with wide experience in managing real-time ethical hacking/ cyber security projects. Indian Cyber Army implements a blend of academic learning and practical sessions to give the candidate optimum exposure.Ethical hacking training ,
    Ethical hacking course

    ReplyDelete