【问题标题】:CanExecute problem when switching to MVVMLight切换到 MVVMLight 时出现 CanExecute 问题
【发布时间】:2020-05-15 14:29:26
【问题描述】:

我一直在使用从一篇文章 (probably this one) 中复制的RelayCommand,下面的CreateExamCommand 工作正常,CanExecute 绑定到“名称是否为空”。

XAML

<UniformGrid Columns="2" DockPanel.Dock="Bottom">
    <Button Content="Cancel" Command="{Binding CancelCommand}" HorizontalAlignment="Left"/>
    <Button Content="Create" Command="{Binding CreateExamCommand}" HorizontalAlignment="Right"/>
</UniformGrid>

<StackPanel VerticalAlignment="Center">
    <TextBox Name="textBox" Tag="Exam Name" 
             Text="{Binding Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />

Csharp

public RelayCommand CreateExamCommand => new RelayCommand(
  () => CreateExam(Name, Date),
  () => !string.IsNullOrEmpty(_name)
);

但是,我刚刚安装了 MVVMLightLibs,以替换我手动复制的代码(并删除了我的 RelayCommand 版本)。现在CreateExamCommandCanExecute方法坏了。

我在CanExecute 中放了一些WriteLines,它似乎只在第一次加载视图(模型)时运行。

我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf mvvm-light


    【解决方案1】:

    这取决于您使用的 MVVMLight 的 RelayCommand 版本。

    如果您有命名空间“GalaSoft.MvvmLight.CommandWpf”,那么您的命令将使用 CommandManager 对象并在每次击键或鼠标单击后自动刷新 CanExecute。

    如果您有“GalaSoft.MvvmLight.Command”,则必须手动触发 CanExecute - 在 Name 属性的设置器中添加 CreateExamCommand.RaiseCanExecuteChanged()

    【讨论】:

    • 其实我只是要开始使用PropertyChanged.Fody。但这个答案绝对是正确和相关的。
    • 使用 Fody.PropertyChanged 的​​几个缺点之一是它不能用作触发器 - 并不是说​​这一定是刷新命令的正确位置。我在我的博客中讨论了另一种方法 - peregrinesview.uk/mvvm-commands
    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    • 2021-07-22
    • 2012-06-10
    • 1970-01-01
    相关资源
    最近更新 更多