I get the DataTable from the database, then fill it with the DataGrid :

 public ICollectionView Item { get { return (ICollectionView)GetValue(ItemProperty); } set { SetValue(ItemProperty, value); } } public static readonly DependencyProperty ItemProperty = DependencyProperty.Register("Item", typeof(ICollectionView), typeof(ViewModel), new PropertyMetadata(null)); public ViewModel() { database = new DBModel(); data = database.GetDataTableProducts(); Item = CollectionViewSource.GetDefaultView(data); } 

XAML data binding:

 <DataGrid x:Name="DataGridProducts" AutoGenerateColumns="True" IsSynchronizedWithCurrentItem="False" ItemsSource="{Binding Item}" SelectedItem="{Binding SelectedItem}"> </DataGrid> 

I need to get the selected row from the DataGrid , but I don't know how to do it.
Data for the DataGrid subject to change (different requests - different DataTable ).

  • one
    Is selectedItem not working or what? - Andrey NOP
  • I don't even know what type I will get. I tried different, but the result is always null - Shader Cat
  • GetType() what does it say? - Andrey NOP
  • Yes, already understood. Thank. (Returns DataRowView) - Shader Cat

1 answer 1

DataGrid (at least in this case) returns the type DataRowView. Further, the necessary data can be retrieved using indexes.

Binding Variable (in ViewModel)

 public DataRowView SelectedItem { get { return (DataRowView)GetValue(SelectedItemProperty); } set { SetValue(SelectedItemProperty, value); } } // Using a DependencyProperty as the backing store for SelectedItem. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(DataRowView), typeof(ViewModel), new PropertyMetadata(null)); 

Then you can use the index to get the data.

 SelectedItem[0] и так далее (номер индекса - номер столбца в DataGrid)