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.
.
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.
You are mixing up your code collections. You take the selected item from
CustomDataGrid.SelectedValue
, but then try to remove that from yourCollection
collection. Try to remove it by data binding another property to theCustomDataGrid.SelectedItem
property and removing that instead:...
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):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 theSelectedItem
property, or an object that is data bound to that property instead.