I have a problem trying to find a way to avoid my ViewModels executing their business logic eg methods calling to database to load tables etc twice. I can see that when I run my application (windows desktop) the ViewModels execute their methods during the startup process of the application and then for those that a user then clicks on a button to bring their View up they execute again. I suspect my issue is that in the ViewModels I have calls in their constructors which then go to a method and this populate the lists by calling to database. IF I remove these methods from the constructors no business logic methods execute on load, however then I cant get the business logic to execute on the button click.
The above duplication of calls causes a long delay for user as one of the database calls takes quite a while eg 10 secs to bring in 7,000 records
I cant think of a way to remove these calls from the constructor but then get the ViewModel to execute these calls when their View is activated via the button on the parent View. Ive given MVVMLight messenger a go but had issues with the sequence. the message would not fire off at right sequence.
I will set out below what I think are the main pieces of code to try and give you an idea of how Ive wired things up. There must be an Industry norm for designing out this issue, but Im not a professional.
MainWindow View with several Child View/ViewModels:
<Window.Resources>
<DataTemplate DataType="{x:Type reports:ReportsTabViewModel}">
<reports:ReportsTabView />
</DataTemplate>
<DataTemplate DataType="{x:Type masterData:MasterDataTabViewModel}">
<masterData:MasterDataTabView />
</DataTemplate>
</Window.Resources>
MainWindow VIewModel is instantiated in the App.xaml.cs:
MainWindow app = new MainWindow();
MainWindowViewModel context = new MainWindowViewModel();
app.DataContext = context;
app.Show();
A series of buttons to bring into View the ViewModel/Views
A ContentControl where they bind when user clicks on their button:
<ContentControl x:Name="PageContentControl" Content="{Binding CurrentPageViewModel}" Grid.Row="1" Grid.RowSpan="2" Grid.Column="1"/>
Then the child View/Models (which are the CurrentPageViewModel):
Child View.xaml which is a UserControl:
<UserControl.DataContext>
<local:PeopleTabViewModel/>
</UserControl.DataContext>
Then the Child ViewModel constructor which fires twice (one call method shown that brings in data from database and is the step I need to avoid being done twice):
public PeopleTabViewModel()
{
FillPeople();
FillModules();
SetPerson();
SetCollectionViews(SelectedPerson.PersonID.ToString());
ChangePerson();
}
private void FillPeople()
{
var q = (from a in db.People
where !a.Archived
orderby a.LastName
select a).ToList();
_people = new List<Person>(q);
}
