Window is loading first then Command is firing when I am using Interactivity

489 views Asked by At

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.

1

There are 1 answers

3
Barracoder On BEST ANSWER

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.