C# 在WPF应用程序中单击按钮从datagrid获取数据
我有一个datagrid,它由一个复选框和两列组成。 当客户单击复选框时,我将触发grid selectionchanged事件,该事件显示从selectedrow到标签的一些数据。 但当我单击按钮时,我也需要所选的行数据C# 在WPF应用程序中单击按钮从datagrid获取数据,c#,wpf,xaml,data-binding,datagrid,C#,Wpf,Xaml,Data Binding,Datagrid,我有一个datagrid,它由一个复选框和两列组成。 当客户单击复选框时,我将触发grid selectionchanged事件,该事件显示从selectedrow到标签的一些数据。 但当我单击按钮时,我也需要所选的行数据 有什么好方法可以检索它吗?根据您的评论,您应该尝试一下(在XAML中,DataGrid被命名为DataGrid): 可以使用标记(编辑:如果您使用CheckBoxColumn,您可以使用样式来执行此操作,如果您对此有问题,我可以给出一个示例): 按钮是否是网格的一部分?是否
有什么好方法可以检索它吗?根据您的评论,您应该尝试一下(在XAML中,
DataGrid
被命名为DataGrid
):
可以使用
标记
(编辑:如果您使用CheckBoxColumn,您可以使用样式来执行此操作,如果您对此有问题,我可以给出一个示例):
按钮是否是网格的一部分?是否假定在单击按钮之前会选择有问题的行?按钮是网格的热门部分。它位于底部。按钮不是网格的一部分。它是独立的。实际上,datagrid.selecteditem是我想要的,我想这就是我想要的。我无法实现这一点,但只调用datagrid.SelectedIndex就行了,因为单击按钮也会选择行。然而,在我的例子中,按钮是网格的一部分。但是如果你在网格外有一个按钮,我想你一定也在网格中选择了一个项目,所以它仍然可以工作。
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;
}
<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;
//...
}