在WPF应用程序中单击按钮时从datagrid获取数据

时间:2011-04-29 20:03:12

标签: c# wpf xaml data-binding datagrid

我有一个数据网格,它由一个复选框和几列组成。 当客户点击复选框时,我将触发grid selectionchanged事件,该事件会将selectrow中的一些数据显示给标签。 但是当我点击按钮时,我还需要选择的行数据。

有什么好办法可以检索吗?

1 个答案:

答案 0 :(得分:6)

根据您的评论,您应该尝试这一点(DataGrid在XAML中被命名为dataGrid

private void Button1_Click(object sender, RoutedEventArgs e)
{
    // If the grid is populated via a collection binding the SelectedItem will
    // not be a DataGridRow, but an item from the collection. You need to cast
    //  as necessary. (Of course this can be null if nothing is selected)
    var row = (DataGridRow)dataGrid.SelectedItem;
}

可以使用Tag编辑:如果您使用CheckBoxColumn,您可以使用样式执行此操作,如果您遇到问题我可以提供示例):

<DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Click="Button1_Click"
                    Tag="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
private void Button1_Click(object sender, RoutedEventArgs e)
{
    var button = (FrameworkElement)sender;
    var row = (DataGridRow)button.Tag;
    //...
}