简体   繁体   中英

Bind a Button to an object in DataGrid WPF

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 Product s, 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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM