首页 > 解决方案 > 如何使用 MVVM 模式在 WPF 中正确实现 ICommand?

问题描述

我正在尝试使用 MVVM 模式做一个简单的 WPF 应用程序。我写了一个实现 ICommand 接口的类:

public class RelayCommand : ICommand
    {
        private Action<object> execute;
        private Func<object, bool> canExecute;

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return this.canExecute == null || this.canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            this.execute(parameter);
        }
    }

然后我使用它,当我单击视图中的按钮时,通过将页面分配给当前页面来显示新页面

public ICommand bFirst_Click
    {
        get
        {
            return new RelayCommand(o => CurrentPage = first);
        }
    }

XAML 代码在视图中

    <StackPanel>
        <Button Command="{Binding bFirst_Click}" Content="First"/>
    </StackPanel>
    <Frame
        Grid.Column="1"
        Content="{Binding CurrentPage}"
        NavigationUIVisibility="Hidden"
        Opacity="{Binding FrameOpacity}"
        />

但什么也没有发生。请帮助我,我是否错过了什么,或者以错误的方式做事?

标签: c#wpfmvvmicommand

解决方案


推荐阅读