Reputation: 1410
Good day! I try to remove selected item from ObservableCollection, but after that- collection becomes null!
private void btDelParameter_Click(object sender, RoutedEventArgs e)
{
var selectedItem = dgParametrs.SelectedItem as Row;
if (selectedItem != null)
{
if (_viewModel.ObjectViewNodel.RowInputColl != null)
{
if(_viewModel.ObjectViewModel.RowInputColl.Contains(selectedItem))
_viewModel.ObjectViewModel.RowInputColl.Remove(selectedItem); //after that RowInputColl is null!
}
else _viewModel.ObjectViewModel.RowInputColl = new ObservableCollection<Row>();
}
}
Some part of XAML code:
<DataGrid AutoGenerateColumns="False"
Name="dgParametrs"
CanUserAddRows="False"
CanUserDeleteRows="False"
IsEnabled="True"
IsReadOnly="False"
SelectedItem="{Binding ObjectViewModel.RowInputColl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
>
...
It is very strange for me,it works fine at last time.
Please, help me with that problem! What i should do, that collection does not becomes null after remove item!
Thank you!
SOLUTION: it was old code- so at that old code need to use SelectedItem. But, at now- i change SelectedItem to ItemsSource- and it works! Thank you!:)
Upvotes: 0
Views: 717
Reputation: 586
I am slightly confused with you code looks. So from your Xaml code, I can see the you have binded SelectedItem to ObjectViewModel.RowInputColl
. So I am assuming its an Item from a Collection
<DataGrid AutoGenerateColumns="False"
Name="dgParametrs"
CanUserAddRows="False"
CanUserDeleteRows="False"
IsEnabled="True"
IsReadOnly="False"
*SelectedItem="{Binding ObjectViewModel.RowInputColl,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"*
>
But now, when I go to your C# code. You are trying to Remove from the same item you binded to SelectedItem ObjectViewNodel.RowInputColl
. You need to Bind ItemsSource property to the collection
and then create a selected Item property in your view model
to bind to selected item. Then remove SelectedItem from collection.
var selectedItem = dgParametrs.SelectedItem as Row;
if (selectedItem != null)
{
if (_viewModel.ObjectViewNodel.RowInputColl != null)
{
if(_viewModel.ObjectViewModel.RowInputColl.Contains(selectedItem))
_viewModel.ObjectViewModel.RowInputColl.Remove(selectedItem); //after that RowInputColl is null!
}
else
{
_viewModel.ObjectViewModel.RowInputColl = new ObservableCollection<Row>();
}
}
Upvotes: 2