我有一个数据网格,它由一个复选框和几列组成。 当客户点击复选框时,我将触发grid selectionchanged事件,该事件会将selectrow中的一些数据显示给标签。 但是当我点击按钮时,我还需要选择的行数据。
有什么好办法可以检索吗?
答案 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;
//...
}