将Button绑定到DataGrid WPF中的对象

时间:2015-01-28 09:32:46

标签: c# wpf datagrid

我正在构建一个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>

1 个答案:

答案 0 :(得分:2)

您可以将产品绑定到Tag属性Button,如下所示:

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

您将获得原始实体:

Product product = button.Tag as Product