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>

5
  • You want to do in MVVM way? Commented Jan 28, 2015 at 9:37
  • 4
    stackoverflow.com/questions/1168976/… Commented Jan 28, 2015 at 9:40
  • @paul, thanks. just saw that post too. Commented Jan 28, 2015 at 9:42
  • @Sajeetharan paul's link gives me a good solution. just curious, what's the MVVM way like? Commented Jan 28, 2015 at 9: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 Commented Jan 28, 2015 at 17:23

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.