c# - 如何使用 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}"
/>
但什么也没有发生。请帮助我,我是否错过了什么,或者以错误的方式做事?
解决方案
推荐阅读
- graphql - 在 shopify 应用开发中自定义 ResourcePicker 数据
- python - 中间件内的烧瓶会话
- flutter - 如何在 Flutter 中向标题 ExpansionTile 添加渐变
- html - html表中列之间的空格太多
- javascript - VueJS:在 Vuex mapAction then 方法中未定义
- jquery - mdbAutocomplete - 新旧自动完成列表的叠加
- c++ - 哪种方式可以更有效地重载运算符,为什么?
- ios - 当媒体段数较少时,AVPlayer 是否播放视频块
- reactjs - 正如我们在 PHP 中使用的那样,如何在 html 元素的属性双引号中使用 JXS?
- arrays - VBA Array/Dictionary IF 公式和 SUMIF