我正在构建一个WPF应用程序,其中包含将项目添加到购物车的操作。定义如下的DataGrid
绑定到Product
s的集合,并且每行都有Button
。现在,当点击Button
时,我如何知道它的 Product
对象?
<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>
答案 0 :(得分:2)
您可以将产品绑定到Tag
属性Button
,如下所示:
<Button Content="Click To Add" Tag="{Binding}"/>
您将获得原始实体:
Product product = button.Tag as Product