0

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...

HyunYoung Go
  • 103
  • 9

1 Answers1

1

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?

Community
  • 1
  • 1
dhilmathy
  • 2,800
  • 2
  • 21
  • 29
  • Actualy I'm new in MVVM, and I'm trying to make without the xaml.cs modifying. So I wanna to modify only View and ViewModel. And.. I read your comment so you mean... Before 'InitializedCommand return part' be activated Initilized event is already triggered.. right? – HyunYoung Go Feb 20 '19 at 01:26
  • MVVM is not about eliminating `xaml.cs` code and it doesn't break the pattern to invoke the `ICommand` from `xaml.cs` of the same view. Coming back to your question, there is no way to handle the `Initialized` event of `FrameworkElement` using an `EventTrigger` that is defined in the XAML of same control. – dhilmathy Feb 20 '19 at 09:13