Good day.

How can I get the index of a row or an instance of a class selected in a DataGrid if the ObservableCollection<Layer> property is passed to it? I would like to implement deleting a string through a button, but I don’t know how to get an index / class instance to remove it from the ObservableCollection<Layer> , it would be desirable to get an instance of the class because you need to pass this name to another method before deleting it in the class.

Short source code

Model

 public class Layer { private string _nameLayer; /// <summary> /// свойство Имени слоя /// </summary> public string NameLayer { get { return _nameLayer; } set { _nameLayer = value; } } private bool _showLayer; public bool ShowLayer { get { return _showLayer; } set { _showLayer = value; } } } 

MainViewModel

  public class MainViewModel:INotifyPropertyChanged { #region PropertyChangedEventHandler /// <summary> /// Метод проверяющий изменилось ли свойство /// </summary> public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion public MainViewModel() { LayerProperties layerProperties = new LayerProperties(); _layersCollection = layerProperties.ReadLayer(); ClickCommandAddLayer = new Command(arg=>{ _layersCollection.Add(layerProperties.AddLayer()); }); ClickCommandDeleterLayer=new Command(arg => { //_layersCollection.Remove(layerProperties.DeleteLayer()); }); } private ObservableCollection<Layer> _layersCollection; public ObservableCollection<Layer> LayersCollection { get { return _layersCollection; } set { _layersCollection = value; } } public ICommand ClickCommandAddLayer { get; set; } public ICommand ClickCommandDeleterLayer { get; set; } } 

View

 <UserControl.Resources> <mainViewModel:MainViewModel x:Key="Vm" /> </UserControl.Resources> <Grid DataContext="{Binding Source={StaticResource Vm}}"> <Grid.RowDefinitions> <RowDefinition Height="20" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <!-- Добавляем разметку для кнопок --> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="20" /> <ColumnDefinition Width="20" /> <ColumnDefinition Width="20" /> <ColumnDefinition Width="20" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Button Name="AddLayer" Grid.Column="0" Command="{Binding ClickCommandAddLayer}" Cursor="Hand" ToolTip="Создать новый слой"> <StackPanel Orientation="Horizontal"> <Image Source="../../Source_Icons/PropertiesLayers/Create.png" /> </StackPanel> </Button> <Button Name="DeleterLayer" Grid.Column="1" Command="{Binding ClickCommandDeleterLayer}" ToolTip="Удалить слой"> <StackPanel Orientation="Horizontal"> <Image Source="../../Source_Icons/PropertiesLayers/Deliter.png" /> </StackPanel> </Button> </Grid> <!-- Отображение в Таблице свойста слоев --> <DataGrid Name="Layers" Grid.Row="1" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" HorizontalGridLinesBrush="#FFE4DDDD" ItemsSource="{Binding Path=LayersCollection, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalGridLinesBrush="#00000000"> <DataGrid.Columns> <DataGridTextColumn Width="*" Binding="{Binding NameLayer}" Header="Название слоя" /> <DataGridCheckBoxColumn Width="auto" Binding="{Binding ShowLayer}" Header="Выкл" /> </DataGrid.Columns> </DataGrid> </Grid> 

    2 answers 2

    Create a Layer type SelectedLayer property:

     private Layer selectedLayer; public Layer SelectedLayer { get { return selectedLayer; } set { selectedLayer = value; OnPropertyChanged("SelectedLayer"); } } 

    Delete as follows:

     layersCollection.Remove(selectedLayer); 

    in xaml:

     <DataGrid ItemsSource="{Binding LayersCollection}" SelectedItem="{Binding SelectedLayer}"/> 
    • Thank you very much. Chet did not think of it himself. - KJfe
    • @Kjfe, please. I am glad to help! - Gardes

    XAML

     <DataGrid Name="MainDataGrid" /> <Button Click="DeleteItem" Grid.Row="1">Delete Row</Button> 

    Codebegind

     private ObservableCollection<Node> collection = new ObservableCollection<Node> { new Node(), new Node() }; private void DeleteItem(object sender, RoutedEventArgs e) { if (MainDataGrid.SelectedItem is Node node && MessageBox.Show($"Delete Row {node.Name} ?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes) { collection.Remove(node); } } 

    Class

     public class Node { public string Name { get; set; } = "Default Name"; } 
    • What dizlike? The object selected in datagrid is received and deleted via a button, as requested by the author - Denis Mochalov