0

I am using the following code to call LoadCommand in ViewModel during loading my window.

<code>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding LoadCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>   
</code>

But what I am seeing is Window is loading before LoadCommand fires.So my code which I have put in my LoadCommand

public ICommand LoadCommand
{
    get
    {
        if (_loadCommand == null)
        {
            _loadCommand = new RelayCommand(
                param => this.Load(),
                param => this.CanLoad
                );
        }
        return _loadCommand;
    }
}
List<Match> matchList;
ObservableCollection<Match> _matchObsCollection;

public ObservableCollection<Match> MatchObsCollection
{
    get { return _matchObsCollection; }
    set
    {
        _matchObsCollection = value;
        OnPropertyChanged("MatchObsCollection");
    }
}
public void Load()
{
    matchList = matchBLL.GetMatch();

}
bool CanLoad
{
    get { return true; }
}

fires after my window loads.If I put my code in constructor of my ViewModel then it fires before the Window loads. I want to know how in MVVM I can make the command fire first and load the Window second. Thanking you in advance.

Abe Heidebrecht
  • 30,090
  • 7
  • 62
  • 66
Anindya
  • 2,616
  • 2
  • 21
  • 25

1 Answers1

1

The problem seems to be that the window has loaded before your ViewModel has been instantiated and bound to the DataContext. The solution is to instantiate your ViewModel before your View.

var vm = new MyViewModel();
var view = new MyView();
view.DataContext = vm;
view.Show();

Don't use a framework that instantiates the view and then "discovers" the applicable viewmodel, at least not in this case.

Barracoder
  • 3,696
  • 2
  • 28
  • 31
  • I am doing the same in my app.xaml.cspublic partial class App : Application { MainWindowViewModel mainWindowVM = new MainWindowViewModel(); MainWindow mainWindow = new MainWindow(); protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); mainWindow.DataContext = mainWindowVM; mainWindow.Show(); } } – Anindya Aug 09 '13 at 05:12
  • This is sill an issue sometimes. I am forced to execute my command in the code behind because the interactivity trigger is triggered before DataContext is set. Looks like it is some kind of timing issue. Any other ides on how to make this work using interactivity? – Stefan Vasiljevic Apr 14 '15 at 13:28
  • What event are you trying to capture Stefan? And what is it exactly that you're trying to do? EventTriggers are, in my opinion, a last resort. – Barracoder Apr 16 '15 at 13:59