简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM