Search code examples
wpfprismdelegatecommand

wpf DelegateCommand return not fire


I'm using Mvvm pattern and in View when the UserControl-Initialized event is binding to InitializedCommand as below.

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Initialized">
        <prism:InvokeCommandAction Command="{Binding Path=InitializedCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

and ViewModel as below.

public DelegateCommand InitializedCommand
{
    get
    {
       SelectedPopupType = PopupTypes.Downloading;
       IsShowPopup = true;
       return new DelegateCommand(delegate ()
       {
          *** DoSomething...***
       }
    }
}

Other events(Loaded,Unloaded..) return parts are working properly but Initialized Command return does not work (DoSomething not called)..

I wonder whats the reason...


Solution

  • As the event name clearly says, Initialized event will get triggered before your Triggers were set via a AttachedProperty. Whereas Loaded event will work, as it is triggered after all your property values were assigned and loaded. So, this won't work.

    Microsoft documentation says:

    If you do not need to read element properties, intend to reset properties, and do not need any layout information, Initialized might be the better event to act upon.

    If you need all properties of the element to be available, and you will be setting properties that are likely to reset the layout, Loaded might be the better event to act upon.

    Also, why do you want to invoke a ICommand for a Initialized event? Why can't you have a EventHandler at your code-behind for this?