【发布时间】:2016-02-11 06:30:16
【问题描述】:
我刚刚尝试将我的一个 WPF 项目从 MVVM Light 4.2.30 更新到 5.2。之后我注意到我的RelayCommands 不再触发他们的CanExecute 方法。
快速搜索后,我找到了几篇解释问题的文章,并建议使用GalaSoft.MvvmLight.CommandWpf 命名空间而不是GalaSoft.MvvmLight.Command。但是我找不到 GalaSoft.MvvmLight.CommandWpf 命名空间。当我在 Visual Studio 的“对象浏览器”中查看 GalaSoft.MvvMGalaSoft.MvvmLight.dll 时,我也找不到这个命名空间。
似乎没有其他人,但我有这个问题 - 知道我做错了什么吗?
更新:
我创建了一个小型示例项目,展示了我当前如何在 MVVM light 版本 4.2.30 中使用 RelayCommands 及其 CanExecute 方法:
public class ViewModel : ViewModelBase
{
private bool _isReadOnly = false;
public ViewModel ()
{
this.DoSomethingCommand = new RelayCommand(DoSomething, CanDoSomething);
}
public bool IsReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
this.RaisePropertyChanged("IsReadOnly");
// With MVVMLight 4.2.30.23246 I did not need to call the RaiseCanExecuteChanged on any of my RelayCommands
// DoSomethingCommand.RaiseCanExecuteChanged();
}
}
public RelayCommand DoSomethingCommand { get; set; }
private bool CanDoSomething()
{
return !this.IsReadOnly;
}
private void DoSomething()
{
MessageBox.Show("Let's break the MVVM idea...");
}
}
视图的 XAML 代码是:
<Window x:Class="MVVMLight5.2CanExecuteTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVMLight5._2CanExecuteTest"
mc:Ignorable="d"
Title="Test" Height="150" Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox HorizontalAlignment="Center" Grid.Row="0" Grid.Column="0" Content="Is read only" IsChecked="{Binding IsReadOnly, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<Button Grid.Row="1" Grid.Column="0" Content="Break me" Command="{Binding DoSomethingCommand}"/>
</Grid>
我的目标是,如果我在视图中有一个使用“DoSomethingCommand”作为命令的按钮,那么当我的 IsReadOnly 属性设置为 false 时,该按钮应该被禁用。 当使用 MVVM light 4.2.30 时,到目前为止没有任何额外的工作,但在 MVVM light 5.2 中我需要添加 DoSomethingCommand.RaiseCanExecuteChanged();使按钮在视图中处于禁用状态。
我可以通过新的 MVVM 轻框架以某种方式获得旧行为吗?
【问题讨论】:
-
只有当您引用库的 PCL(便携式)版本时,
RelayCommand类才位于CommandWpf命名空间中。当面向 .NET 4.0 及更低版本时,它位于Command命名空间中。你确定是 MvvmLight 有错吗?能贴出代码吗? -
不,我没有使用便携式版本 - 我正在引用库的常规 4.5 版本。为什么这仅适用于 PCL 版本且仅适用于 .NET 4.0?那我该如何解决我的问题呢?
-
目前没有找到答案。与此同时,我想知道在当前版本的 MVVM light 中如何调用 CanExecute 方法:手动?也许在一个计时器内?
-
能否贴出用于绑定命令的代码,以及创建命令的代码和
CanExecute方法本身?我对此没有任何问题,并且我不知道当前没有调用CanExecute的任何错误。要么创建一个 SSCCE 来展示错误。 -
嗨帕特里克!对不起,后来的回答......我已经更新了我的帖子。
标签: c# wpf mvvm mvvm-light relaycommand