DataGrid获取选定行的列值

Pri*_*ner 34 .net c# wpf datagrid

我正在尝试获取DataGrid中所选行的每列的值.这就是我所拥有的:

private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataGrid dg = sender as DataGrid;
    Console.WriteLine(dg.SelectedCells[0].ToString());
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用.如果我这样做,SelectedCells.Count那么我得到正确的列数,但我似乎无法实际获得所选行中这些列的值.我已经尝试了一段时间没有运气!这是我的XAML:

<Grid>
    <DataGrid CanUserAddRows="True" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Stretch" Margin="12,12,79,0" Name="dataGrid1" VerticalAlignment="Top" Width="389" DataContext="{Binding}" CanUserResizeColumns="False" CanUserResizeRows="False" HorizontalContentAlignment="Stretch" PreviewMouseDoubleClick="dataGrid1_PreviewMouseDoubleClick" CellEditEnding="dataGrid1_CellEditEnding">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding  Path=UserID}"
                                Header="User ID" Width="SizeToHeader" />
            <DataGridTextColumn Binding="{Binding  Path=UserName}"
                                Header="User ID" Width="SizeToHeader" />
        </DataGrid.Columns>
    </DataGrid>
</Grid>
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想通过做类似的事情来访问数据,rowData.UserID但我似乎无法解决这个问题.有很多教程和使用DataGridView的帮助,但我没有使用它.

Ton*_*ams 62

更新

要获取所选行,请尝试:

IList rows = dg.SelectedItems;
Run Code Online (Sandbox Code Playgroud)

然后,您应该能够从行项目中获取列值.

要么

DataRowView row = (DataRowView)dg.SelectedItems[0];
Run Code Online (Sandbox Code Playgroud)

然后:

row["ColumnName"];
Run Code Online (Sandbox Code Playgroud)


Pri*_*ner 8

基于Tonys的解决方案答案:

        DataGrid dg = sender as DataGrid;
        User row = (User)dg.SelectedItems[0];
        Console.WriteLine(row.UserID);
Run Code Online (Sandbox Code Playgroud)


Phi*_*oie 6

我做了类似的事情,但我使用绑定来获取所选项目:

<DataGrid Grid.Row="1" AutoGenerateColumns="False" Name="dataGrid"
          IsReadOnly="True" SelectionMode="Single"
          ItemsSource="{Binding ObservableContactList}" 
          SelectedItem="{Binding SelectedContact}">
  <DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name"/>
    <DataGridTextColumn Binding="{Binding Path=FamilyName}" Header="FamilyName"/>
    <DataGridTextColumn Binding="{Binding Path=Age}" Header="Age"/>
    <DataGridTextColumn Binding="{Binding Path=Relation}" Header="Relation"/>
    <DataGridTextColumn Binding="{Binding Path=Phone.Display}" Header="Phone"/>
    <DataGridTextColumn Binding="{Binding Path=Address.Display}" Header="Addr"/>
    <DataGridTextColumn Binding="{Binding Path=Mail}" Header="E-mail"/>
  </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

所以我可以在我的ViewModel中访问我的SelectedContact.Name.