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

ali*_*ce7 2 c# data-binding wpf xaml datagrid

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

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

H.B*_*.B. 6

根据你的评论你应该尝试这个(在XAML中DataGrid命名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;
}
Run Code Online (Sandbox Code Playgroud)

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

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