I have googled so much on this topic that my hands are bleeding before writing this question. What I have gathered so far is that I know I have to use an ObservableCollection
.
The ListBox
populates on startup, but the problem occurs when I want to delete/remove an item from the ObservableCollection
and have it reflected in the ListBox
.
The item is removed from the ObservableCollection
but the ListBox
does not update anything. I have tried different bindings like Mode and UpdateSourceTrigger
.
This is my code so far:
<ListBox Name="projectsListBox" ItemsSource="{Binding Projects}"
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,5,0">
<Image Source="{Binding Icon}" Width="20"/>
<TextBlock Text="{Binding ProjectName}" FontSize="14"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ViewModel. The ViewModel inherits from ViewModelBase which in turn inherits from INotifyPropertyChanged.
public class OpenProjectViewModel : ViewModelBase
{
private ObservableCollection<ProjectData> _projects;
public ObservableCollection<ProjectData> Projects
{
get { return _projects; }
set
{
if (_projects != value)
{
_projects = value;
OnPropertyChanged(nameof(Projects));
}
}
}
}
Code that removes the item from the ObservebleCollection
:
Projects
.Remove(Projects
.Where(_ => _.Id == id).Single());
Update: one thing to note is in OpenProjectView
I have a OnDelete_Click
button, I have instantiated the OpenProjectViewModel
which holds the delete logic for the ObservableCollection
. The ObservableCollection
is instantiated in the constructor. Any thoughts on how to get around this?
private void OnDelete_Click(object sender, RoutedEventArgs e)
{
OpenProjectViewModel openProjectViewModel = new();//<--The ObservableCollection is instantiated in the constructor
openProjectViewModel.DeleteProject(listItem);
}
Did I forget to share anything?
Thank you for your assistance!