为什么以下WPF命令不会触发?

时间:2012-11-06 02:42:15

标签: c# .net wpf prism

C#文件:

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文件

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

TestParameter getter上的断点会触发,但TestMethod永远不会触发。

我没有在“输出”窗口中看到任何绑定错误(相反,如果我故意拼写错误拼写TestCommand2它会抱怨 - 所以我猜这是正确的)

这是使用Prism DelegateCommand和Expression Blend InvokeCommandAction行为

2 个答案:

答案 0 :(得分:2)

发现问题......这是一个排序问题 - 我在InitializeComponent()之后分配了命令,导致处理XAML(因此首先评估绑定表达式 - 此时TestCommand属性仍为NULL)< / p>

我这个愚蠢的新手错误。

答案 1 :(得分:1)

我在自己的ICommand实现中遇到了类似的问题,原因是在命令的Execute()方法中,它错误地尝试将参数强制转换为{{1}类型以逆变的方式。我不知道Prism T是什么样的,但你可能想调试它的代码来找出答案。否则,我的代码中没有任何错误。

相关问题