blue18hutthutt
blue18hutthutt

Reputation: 3243

Why does the following WPF Command not fire?

C# file:

public partial class MainWindow : Window
{
    public DelegateCommand<ICollection<string>> TestCommand { get; set; }

    public ICollection<string> TestParameter
    {
        get
        {
            List<string> lstParams = new List<string>() { "test", "test2", "test3" };
            return lstParams;
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        TestCommand = new DelegateCommand<ICollection<string>>(TestMethod);
    }

    private void TestMethod(ICollection<string> param)
    {
        if (param != null)
        {
            lblTest.Content = "Hit";
        }
    }
}

.XAML file

<Window x:Class="WPFAttachedBehaviorTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:local="clr-namespace:WPFAttachedBehaviorTest"
    Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Loaded">
        <i:InvokeCommandAction CommandParameter="{Binding Path=TestParameter}" Command="{Binding Path=TestCommand}" />
    </i:EventTrigger>
</i:Interaction.Triggers>
<Label x:Name="lblTest"></Label>
</Window>

A break point on the TestParameter getter fires but TestMethod never fires.

I don't see any binding errors in the Output window (on the contrary, if I deliberately mis-spell TestCommand2 it'll complain - so I guess this is correct)

This is using the Prism DelegateCommand and the Expression Blend InvokeCommandAction behavior

Upvotes: 0

Views: 1693

Answers (2)

blue18hutthutt
blue18hutthutt

Reputation: 3243

Found the problem ... it was a sequencing problem - I assigned the command after the InitializeComponent() causing the XAML to be processed (and thus evaluating the binding expressions first - at this point the TestCommand property is still NULL)

Stupid newbie mistake on my part.

Upvotes: 2

Fede
Fede

Reputation: 44038

I had a similar problem with my own implementation of ICommand, caused by the fact that in the Execute() method of the command, it was incorrectly trying to cast the parameter to type T in a contravariant way. I don't know what does the Prism DelegateCommand<T> look like, but you may want to debug into its code to find out. Otherwise I don't see any errors in your code.

Upvotes: 1

Related Questions