Passing Command Parameter for Buttons within an ItemTemplate using MVVM Pattern in WPF

Introduction

In this tip, we will talk about how to pass a CommandParameter for a Button control which is used within theItemTemplate of the ListBox control. We are trying to load the list of Buttons inside the ListBox. The list of Buttons is in English and Danish language. This tip will help you to identify which Button has been pressed and how to pass the CommandParameter within the Button control in MVVM.

Background

Suppose we have three buttons and each Button has its own command in the ViewModel. Then it can be done by adding three different ICommand properties in the ViewModel and bind those commands inside the XAML to the respective Button controls. This is the very straight forward approach in MVVM model.

Now the scenario is we want to display a list of Buttons at run time that is dynamically add Buttons into the List. We can add the Button control inside the DataTemplate and use this Template as a StaticResource of theItemTemplate.

<UserControl.Resources>
    <DataTemplate x:Key="UserTemplate1">
    <Button x:Name="button1"Command="{Binding RelativeSource=
    {RelativeSource AncestorType=UserControl},Path=DataContext.OnButtonClickCommand}"/>
    </DataTemplate>
</UserControl.Resources>

In Grid – Use this DataTemplate:

<ListBox ItemTemplate="{StaticResource UserTemplate1}"/>

NoteOnButtonClickCommand is ICommand property inside the ViewModel.

This will help us to add multiple Buttons inside the ListBox by providing an ItemsSource. But here is one problem, what if there are three buttons named as Save, Open, and Close. And the requirement is that each Button click event will perform a different functionality. All these buttons have a single Command value OnButtonClickCommand. Then it is very difficult to identify in the ViewModel which Button is pressed from the Buttons list.

To solve the above problem, we need to pass a CommandParameter for the Button control to identify which Buttonis currently pressed.

<DataTemplatex:Key="UserTemplate1">
     <Buttonx:Name="button1" Command="{Binding RelativeSource={RelativeSource
     AncestorType=UserControl},Path=DataContext.OnButtonClickCommand}" 
     CommandParameter ="{Binding ElementName=button1}"/>
</DataTemplate> 

Read More.
Advertisements
By Sriramjithendra Posted in WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s