jason
jason

Reputation: 7164

How to bind a command to Window Loaded event using WPF and MVVM

There is a button which is binded to a command like this on my WPF window :

<Button Command="{Binding SearchCommand}">

I want that Command to be executed when that window is loaded. I added this to xaml :

Loaded="DXWindow_Loaded">

And I added this to code-behind, but I don't know what to write to fill the method.

private void DXWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
{

}

How can I call that SearchCommand or SearchExecute from code-behind? Thanks.

Upvotes: 0

Views: 1178

Answers (1)

I assume that you bind your ViewModel to your View's DataContext.

var vm = this.DataContext as YourViewModel;
vm.SearchCommand.Execute(null);

Upvotes: 1

Related Questions