Question

EventToCommand fails to pass Command Parameter on Load Event

When attached to the Load event of the page or user control the EventToCommand successfully calls the handler in the ViewModel but does not pass the CommandParameter. However, the same XAML is attached to another event, button click for example, the Command handler receives the databound data as its parameter. Xaml:

<i:EventTrigger EventName="Loaded" SourceObject="{Binding ElementName=Control}"> <Command:EventToCommand x:Name="etcLoad" Command="{Binding LoadCommand}" CommandParameter="{Binding Target, ElementName=Control}" /> </i:EventTrigger>

Target is a string DP on the View.

VM Code:

    internal void Load(string p_Param)
    {
        this.Initialise();
    }

    public RelayCommand<string> LoadCommand { get; private set; }

and the Command is assigned so:

    this.LoadCommand = new RelayCommand<string>(this.Load);

I am almost certain that the problem lies with the binding being done later than the assignment to the Target DP or something similar. I am interested in finding a solution for this ASAP or some other way that I might get a string out of the View and into the ViewModel where the string is assigned from the OnNavigateTo override. The goal is to provide the selection of a tab based on a query property supplied via the URI i.e. "/Views/DisplayTabDetails?Tab=Tab1" or similar.

Was it helpful?

Solution

Use the PassEventArgsToCommand property to indicate that the event args should be passed to the command. In your XAML you should, therefore, use:

<i:EventTrigger EventName="Loaded" 
                SourceObject="{Binding ElementName=Control}"> 
    <Command:EventToCommand x:Name="etcLoad" 
                            Command="{Binding LoadCommand}" 
                            PassEventArgsToCommand="True" /> 
</i:EventTrigger>

Edit

Some events fire before the user interaction can take place. The approach normally taken in this case is to call your command from code behind. In this post you can see the concept, you obviously will have to change it to the loaded event and your needs, the concept and the reason for it are the same, though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top