[WPF] How to avoid calling initial methods in the view model’s constructor

Posted by William Basics on Friday, April 1, 2022

Introduction

When developing a WFP application in the MVVM way, we often need to initialize such as loading data, logging, and other kinds of stuff when the view model is created.

The no-brain way is to call the “initialization” method directly in the view model’s constructor while hoping the calling method never fails and finishes instantly.

public class AwsomeViewModel {
	public AwsomeViewModel () {
		LoadDataFromDatabase();
	}
}

However, To call a method that is likely to fail or costs a long time is a bad practice in any way. So we should avoid doing that.

But how?

In WPF, all UI elements have events related to their lifetime. So the solution is we bind a command to that event. When the “initial” event comes, our self-defined command will be called.

To be more specific, almost every view has a Grid. And the Grid is derived from the FrameworkElement. And the FrameworkElement has a Loaded event. It is the event we want to bind.

So in view, we code like this:

<UserControl ....
		...
		xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
		...
>
	<Grid>
			<b:Interaction.Triggers>
        <b:EventTrigger EventName="Loaded">
          <b:InvokeCommandAction Command="{Binding LoadCommand}"/>
        </b:EventTrigger>
      </b:Interaction.Triggers>
		...
	</Grid>

</UserControl>

And in the view model, we declare the LoadCommand

public class AwsomeViewModel {
	public ICommand LoadCommand { get; set;}

	public AwsomeViewModel () {
		LoadCommand = new DelegateCommand(OnLoaded);
	}

	private void OnLoaded() {
		LoadDataFromDatabase();
	}
}

Coding like this, we get a “never” fail constructor and move the method calling out. 😊

(end.)