简体   繁体   English

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

[英]Why does the following WPF Command not fire?

C# file: 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 file .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>

A break point on the TestParameter getter fires but TestMethod never fires. TestParameter getter上的断点触发,但TestMethod从不触发。

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) 我在“输出”窗口中没有看到任何绑定错误(相反,如果我故意拼写错误的TestCommand2,它将抱怨-所以我想这是正确的)

This is using the Prism DelegateCommand and the Expression Blend InvokeCommandAction behavior 这是使用Prism DelegateCommand和Expression Blend InvokeCommandAction行为

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) 发现了问题……这是一个排序问题-我在InitializeComponent()之后分配了导致处理XAML的命令(并因此首先评估了绑定表达式-此时TestCommand属性仍然为NULL)

Stupid newbie mistake on my part. 我这是愚蠢的新手错误。

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. 我自己的ICommand实现也遇到了类似的问题,原因是在命令的Execute()方法中,它错误地试图以相反的方式将参数转换为T类型。 I don't know what does the Prism DelegateCommand<T> look like, but you may want to debug into its code to find out. 我不知道Prism DelegateCommand<T>什么样子,但是您可能需要调试其代码以找出答案。 Otherwise I don't see any errors in your code. 否则,我不会在您的代码中看到任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM