1

I am building a WPF app where it includes an action of adding an item to a shopping cart. A DataGrid defined as follows is bind to a collection of Products, and a Button is present for each row. Now, when a Button is clicked, how do I know which Product object it is for?

<DataGrid Grid.Row="1" ItemsSource="{Binding }" IsReadOnly="True" IsSynchronizedWithCurrentItem="True" 
              AutoGenerateColumns="False" TextBlock.FontSize="20" CanUserSortColumns="True" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Header 1" Binding="{Binding ID}" Width="2*" SortMemberPath="{Binding ID}"/>
        <DataGridTextColumn Header="Header 2" Binding="{Binding Name}" Width="2*" SortMemberPath="{Binding Name}"/>

        <DataGridTemplateColumn Header="Add To Cart" Width="2*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Click To Add"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

stsur
  • 206
  • 2
  • 9
totoro
  • 3,257
  • 5
  • 39
  • 61
  • You want to do in MVVM way? – Sajeetharan Jan 28 '15 at 09:37
  • 4
    http://stackoverflow.com/questions/1168976/wpf-datagrid-button-in-a-column-getting-the-row-from-which-it-came-on-the-cli – paul Jan 28 '15 at 09:40
  • @paul, thanks. just saw that post too. – totoro Jan 28 '15 at 09:42
  • @Sajeetharan paul's link gives me a good solution. just curious, what's the MVVM way like? – totoro Jan 28 '15 at 09:43
  • I think you can override Product class and have there a method, which will handle buttonClick. So when you will create a command for datagridrowButtonClick it will be binded to your method in ProductClass – Sasha Jan 28 '15 at 17:23

1 Answers1

3

You can bind Product to Tag Property of Button Like this :

<Button Content="Click To Add" Tag="{Binding}"/>

You will get original entity by :

Product product = button.Tag as Product
Amol Bavannavar
  • 2,062
  • 2
  • 15
  • 36