c# - 为什么不调用 RelayCommand?

标签 c# wpf mvvm relaycommand

我的 ViewModel 中有以下内容:

public MyViewModel() {
  CloseCommend = new RelayCommand(closeWindow);
}

public RelayCommand CloseCommend;
private void closeWindow() {
  Application.Current.MainWindow.Close();
}

XAML:
<Button ... Command="{Binding CloseCommend}"/>

我看到 ViewModel 构造函数已初始化,因此绑定(bind)应该在那里。但是当我点击关闭按钮时,什么也没有发生。任何想法我做错了什么?

最佳答案

从字段定义更改为属性定义:

public RelayCommand CloseCommand { get; set; }

为什么:

字段通常是不可绑定(bind)的。查看 Binding Sources Overview

You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object. The binding engine uses CLR reflection to get the values of the properties. Alternatively, objects that implement ICustomTypeDescriptor or have a registered TypeDescriptionProvider also work with the binding engine.

For more information about how to implement a class that can serve as a binding source, see Implementing a Class for the Binding Source later in this topic.



在“ 其他特性 ”部分下:

You cannot bind to public fields.

关于c# - 为什么不调用 RelayCommand?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39395646/

相关文章:

c# - WinForms.FontDialog 中缺少字体

c# - 短指令有更好的性能吗?

c# - MySql.Data c# .net 库我应该使用哪个运行时?

c# - PropertyChangedEventHandler 是如何工作的?

c# - 如何对具有多个子层的根 ViewModel 进行单元测试?

wpf - 使用 MVVM 从 WPF ListView 项目触发双击事件

c# - 在 C# 中使用条件运算符键入结果

c# - 如何在 ShowDialog() 阻塞调用之前注册消息处理程序?

c# - 添加此项目作为引用会导致循环依赖 mvvm

wpf - 如果内部属性更改,则整个对象的 RaisePropertyChanged