An ObservableCollection of a DependencyProperty is returning null

89 Views Asked by At

I am in a saga for creating a custom control with a datagrid and two buttons, one for add and another for remove elements from the datagrid. Some thing like the picture below.

enter image description here .

Right now my I can add elements and bind the ItemsSorce of the datagrid directly with the Collection of my ViewModel by exposing a DependecyProperty. Here is the code in another Question I have made here. Please consider the @Sandesh corrections.

Now I want to implement the remove button by adding a behaviour that should be the same for every usage: It will remove the selected row of the datagrid. For this I add the above code to the code behind of the CustomDatagrid.xaml:

private void RemoveButtonClick(object sender, RoutedEventArgs e)
        {
            var selectedItem = CustomDataGrid.SelectedValue;

            if (selectedItem != null && Colection != null)
            {
                Colection.Remove(selectedItem);
            }
        }

But when I press the remove button the Colection return null and nothing happens.

Thanks for any help.

1

There are 1 best solutions below

1
On

You are mixing up your code collections. You take the selected item from CustomDataGrid.SelectedValue, but then try to remove that from your Collection collection. Try to remove it by data binding another property to the CustomDataGrid.SelectedItem property and removing that instead:

<DataGrid Name="CustomDataGrid" ItemsSource="{Binding Collection}" 
    SelectedItem="{Binding YourNewSelectedItemProperty}" ... />

...

Colection.Remove(YourNewSelectedItemProperty);

UPDATE >>>

To clarify further:

You can only remove an item from a collection if that exact item actually exists in the collection. In your case, you are using the SelectedValue property which returns (from the linked page):

the value of the SelectedItem, obtained by using SelectedValuePath.

Note that part that I highlighted. This does not necessarily return the actual selected item. In fact, depending on the value of the SelectedValuePath property, it could just return a property of the selected item. Therefore, you should use the SelectedItem property, or an object that is data bound to that property instead.