Ronald
Ronald

Reputation: 2100

EventTrigger on UserControl 'Loaded' not calling ICommand.Execute

I'm trying to execute an ICommand (AsyncRelayCommand) on the loaded event of my UserControl using the Microsoft.Xaml.Behaviors.Wpf library.

<UserControl x:Class="..."
             ...
             xmlns:Behaviors="http://schemas.microsoft.com/xaml/behaviors"
             DataContext="{Binding ViewModel, Source={StaticResource ViewModelLocator}}">
    <Behaviors:Interaction.Triggers>
        <Behaviors:EventTrigger EventName="Loaded">
            <Behaviors:InvokeCommandAction Command="{Binding LoadCommand}" />
        </Behaviors:EventTrigger>
    </Behaviors:Interaction.Triggers>
    ...
</UserControl>

The command property is called correctly, the Command class is created and it also calls correctly the CanExecute method (which returns true).

public override ICommand LoadCommand
{
    get { return new AsyncRelayCommand(
              async () => { /*never executed*/ }, 
              () => return !this.IsLoading); // canExecute logic executed (true)
         }
}

But it never calls the Execute method.

I believe I need somehow tell that I want the UserControl's event, but all examples are looking the same as mine.

Upvotes: 1

Views: 844

Answers (1)

ΩmegaMan
ΩmegaMan

Reputation: 31616

I believe the design as described, does not adhere to separation of concerns between the user control and an external viewmodel.

I would instead use the Loaded event of the UserControl and create a specific dependency property on the control which the user will have bound the ICommand to when wiring up the control.

Example

    #region public ICommand LoadCommand
    /// <summary></summary>
    public ICommand LoadCommand
    {
        get => GetValue(LoadCommandProperty) as ICommand;
        set => SetValue(LoadCommandProperty, value);
    }

    /// <summary>
    /// Identifies the LoadCommand dependency property.
    /// </summary>
    public static readonly DependencyProperty LoadCommandProperty =
        DependencyProperty.Register(
            "LoadCommand",
            typeof(ICommand),
            typeof(MainUserControl),
            new PropertyMetadata(null));
    #endregion public ICommand LoadCommand


    private void MainUserControl_OnLoaded(object sender, RoutedEventArgs e) 
        => LoadCommand?.Execute(null); 

Upvotes: 1

Related Questions