Home > Software design >  Updating listviews when db updates
Updating listviews when db updates

Time:11-05

I'm new at MVVM and I have a problem with updating lists.

I have 2 windows and ListViews in it. They are connected to a property "Tasks". When I add a new row to my db I need to refresh ListViews. I've done it, but only for 1 window.

adding a new row to a db table

private void OnAddTaskExecuted(object p)
        {
            tasks tsk = new tasks()
            {
                taskname = "1",
                description = "",
                date = DateTime.Now,
                empID = 2
            };
            Core.db.tasks.Add(tsk);
            Core.db.SaveChanges();
            Tasks = new ObservableCollection<tasks>(Core.db.tasks); 
            //it updates only in the window from which I'm adding the row
        }

viewmodel ctor

public MainWindowViewModel()
        {
            AddTask = new RelayCommand(OnAddTaskExecuted, p => true);
            Tasks = new ObservableCollection<tasks>(Core.db.tasks);
        }

So after clicking a btn I have this situation. ListView updates only in window where I click, but not in another (the new tasks is the first one)img

P.S. I have 2 same windows, I just making a new same window by btn click. That is just for a test. I'm actually creating a big project with lots of pages in it, and I need to update every Collection that have tasks in it.

CodePudding user response:

Your issue is that you have two different Window instances with separate instances of ObservableCollection<tasks> Tasks

There are several ways in dotnet to structure your data in a persistent manner. Here are some:

  1. Assuming both Windows are of the same type, the easiest way is to just make Tasks a static field.

  2. Create a separate class, eg. called "TaskManager", with a field Tasks, and use that. If TaskManager is a static class, you don't have to bother with organizing any instances. Alternatively, there are concepts like Singletons. You can also store your data, or objects containing your data inside App.xaml.cs, where you can then access it via Application.Current.SomeField

If you want to reuse the same Window instance instead of storing your data somewhere else, that really depends on how you navigate to your Window. If you open your Window with something like this...

MyWindow window = new MyWindow();
window.Show();

... then you'll have to store your WindowInstance in a persistent manner as explained above, instead of instanciating a new one with new MyWindow() every time you want to show it.

  • Related