WPF RelyCommand绑定但不执行?

问题描述

| 我有一个绑定到视图模型的命令,已启用,但并不总是执行。我该如何调试呢?我使用了WPF Inspector,它重新确认了绑定是正确的。 更多详情: 我有一个选项卡控件,该控件仅在未选择选项卡时才执行关闭选项卡的命令。选择选项卡后,命令将不起作用。 该代码是相当标准的,我似乎看不到或调试探针。 TabItem上的模板化关闭按钮
                <Style x:Key=\"ClosableStyle\" targettype=\"telerik:RadTabItem\">
                <Setter Property=\"HeaderTemplate\">
                    <Setter.Value>
                        <DataTemplate>
                            <Grid>
                                <Grid.ColumnDeFinitions>
                                    <ColumnDeFinition Width=\"*\"/>
                                    <ColumnDeFinition Width=\"Auto\"/>
                                </Grid.ColumnDeFinitions>
                                <ContentControl Grid.Column=\"0\" Content=\"{Binding displayName}\"/>
                                <telerik:RadButton Grid.Column=\"1\" Margin=\"3 1 -4 0\" Width=\"16\" Height=\"16\" Opacity=\"0.7\" Command=\"{Binding Path=CloseCommand}\">
                                    <TextBlock Text=\"x\" FontFamily=\"Arial Rounded MT\" FontSize=\"12\" Margin=\"0,-3,0\" />
                                </telerik:RadButton>
                            </Grid>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
命令:
RelayCommand _closePanelCommand;
/// <summary>
/// Returns the command that,when invoked,attempts
/// to remove this workspace from the user interface.
/// </summary>
public virtual ICommand CloseCommand
{
    get
    {
        if (_closePanelCommand == null)
        {
            _closePanelCommand = new RelayCommand(
                () =>
                {
                    this.OnRequestClose();
                }
            );
        }

        return _closePanelCommand;
    }
}
    

解决方法

我还建议使用Snoop,它是UI调试实用程序,对于此类调试至关重要。否则,你就瞎了。 用
Button
表示的事情是,如果Command绑定失败(默默发生),则
Button
保持启用状态,因此您不知道按钮是否已启用,因为
ICommand
表示是这样或因为绑定失败。 您还可以查看输出窗口,该窗口应告诉您绑定是否失败,但是snoop比在输出窗口中阅读一堆文本要容易得多:)     ,我想您的问题是您正在尝试将ICommand用作INotifiableProperty,它将无法像这样工作。您需要在ViewModel的构造函数中为命令提供处理程序,如下所示-
this.CloseCommand= new RelayCommand(param => this.OnRequestClose(param));
然后像这样写你的财产-
public ICommand CloseCommand { get; set; }
    ,您应该检查按钮的实际数据上下文(使用Snoop)。我认为,如果您的命令未触发,则datacontext不正确。