c# - RelayCommand CanExecute 行为不起作用

标签 c# wpf mvvm-light

我无法让 RelayCommand 正确启用/禁用附加控件。

我有一个附加到按钮的 EventToCommand 元素。该命令数据绑定(bind)到 ViewModel。最初,该按钮被禁用(预期行为),但我似乎无法获得 CanExecute 逻辑来检查它的值。当设置并存在 CurrentConfigFile 时,应启用该按钮。我已经执行了代码并在调试中检查了文件的值以确保它已设置,但控件仍然被禁用。我试过 CommandManager.InvalidateRequerySuggested()command.RaiseCanExecuteChanged(),但它不会启用。

我想知道 lambda 是否不能为 CanExecute 行为正常工作(即使示例使用了它们)或者 CanExecute 行为是否需要数据绑定(bind)到另一个元素。

这是我的代码:

// The FileInfo being checked for existence before the button should be enabled
public const string CurrentConfigFilePN = "CurrentConfigFile";
public FileInfo CurrentConfigFile
{
    get
    {
        return _currentConfigFile;
    }

    set
    {
        if (_currentConfigFile == value)
        {
            return;
        }

        var oldValue = _currentConfigFile;
        _currentConfigFile = value;

        // Update bindings, no broadcast
        RaisePropertyChanged(CurrentConfigFilePN);
    }
}

public MainViewModel()
{
    // snip //

    SaveCommand = new RelayCommand(SaveConfiguration, 
        () => CurrentConfigFile != null && CurrentConfigFile.Exists);
    }

private void SaveConfiguration()
{

    // export model information to xml document
    ExportXMLConfiguration(CurrentConfigFile);

}

和标记

<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <GalaSoft:EventToCommand x:Name="SaveETC" 
                Command="{Binding SaveCommand}" 
                MustToggleIsEnabledValue="true" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

更新:

根据 Isak Savo 的建议,我将 RelayCommand 直接绑定(bind)到带有

的按钮
<Button x:Name="SaveButton" Content="Save" Width="75" Margin="20,5" 
Command="{Binding SaveCommand}"/>

当设置 FileInfo 时,它开始禁用并正确启用。我想我应该记住不要修复没有损坏的东西!

最佳答案

为什么不直接从按钮绑定(bind)到命令?

<Button Command="{Binding SaveCommand}" Content="Save" />

也许您正在使用的 EventToCommand 与命令的 CanExecute 通知混淆了。

关于 CanExecute 问题 - 您确定在设置 CurrentConfigFile 属性后调用您的 CanExecute 处理程序吗?我发现尽管 WPF 在重新查询 CanExecute 方面做得很好,但有时我仍然需要通过 CommandManager 强制重新查询。 .

编辑:正如评论中所指出的,OP 已经尝试了命令管理器方法。

关于c# - RelayCommand CanExecute 行为不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3755143/

相关文章:

c# - Asmx Web 服务如何返回 JSON 而不是 XML?

wpf - 在 WPF ListBox 中,如何将项目的聚焦选择样式 "copy"转换为非聚焦选择样式?

windows-phone-7 - "Refresh"使用 WP7 的 Mvvm-light 工具包进行枢轴控制

c# - MVVM : RaisePropertyChange on another item in the same list

c# - wpf - 如何控制用户控件鼠标悬停时的可见性?

c# - 更新添加为 HttpClient 的 DefaultRequestHeaders 的自定义 header 值

c# - 根据子节点对整个 xdocument 进行排序

c# - MVVM 了解基础知识

c# - 为什么 ObservableCollection 不支持批量更改?

wpf - wpf mvvm light中的Messenger服务和数据服务有什么区别