C# 为什么下面的WPF命令不触发?

C# 为什么下面的WPF命令不触发?,c#,.net,wpf,prism,C#,.net,Wpf,Prism,C#文件: 公共部分类主窗口:窗口 { 公共DelegateCommand TestCommand{get;set;} 公共ICollection测试参数 { 得到 { List lstParams=newlist(){“test”、“test2”、“test3”}; 返回lstparms; } } 公共主窗口() { 初始化组件(); TestCommand=新的DelegateCommand(TestMethod); } 私有void测试方法(ICollection参数) { 如果(参数!=

C#文件:

公共部分类主窗口:窗口
{
公共DelegateCommand TestCommand{get;set;}
公共ICollection测试参数
{
得到
{
List lstParams=newlist(){“test”、“test2”、“test3”};
返回lstparms;
}
}
公共主窗口()
{
初始化组件();
TestCommand=新的DelegateCommand(TestMethod);
}
私有void测试方法(ICollection参数)
{
如果(参数!=null)
{
lblTest.Content=“点击”;
}
}
}
.XAML文件

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";
        }
    }
}

TestParameter getter上的断点会激发,但TestMethod不会激发

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


这是使用Prism DelegateCommand和表达式Blend InvokeCommandAction behavior时,我自己的
ICommand
实现也遇到了类似的问题,原因是在命令的
Execute()
方法中,它错误地试图以逆变方式将参数强制转换为类型
T
。我不知道Prism
DelegateCommand
是什么样子的,但是您可能需要调试到它的代码中才能找到答案。否则,我看不到您的代码中有任何错误。

我自己的
ICommand
实现也有类似的问题,原因是在命令的
Execute()
方法中,它错误地试图以反变方式将参数强制转换为type
t
。我不知道Prism
DelegateCommand
是什么样子的,但是您可能需要调试到它的代码中才能找到答案。否则,我看不到您的代码中有任何错误。

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


我犯了愚蠢的新手错误。

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

我犯了一个愚蠢的新手错误

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