简体   繁体   English

为什么不调用RelayCommand?

[英]Why isn't RelayCommand called?

I have the following in my ViewModel: 我的ViewModel中有以下内容:

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

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

XAML: XAML:

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

I see the ViewModel constructor is initialized so the binding should be there. 我看到ViewModel构造函数已初始化,因此绑定应该在那里。 But when I click the close button, nothing happens. 但是当我单击关闭按钮时,什么也没有发生。 Any ideas what I'm doing wrong? 有什么想法我做错了吗?

Change from a field definition to a property definition: 从字段定义更改为属性定义:

public RelayCommand CloseCommand { get; set; }

Why: 为什么:

Fields are typically, not bindable. 字段通常是不可绑定的。 Check out the Binding Sources Overview 查看绑定源概述

You can bind to public properties, sub-properties, as well as indexers, of any common language runtime (CLR) object. 您可以绑定到任何公共语言运行时(CLR)对象的公共属性,子属性以及索引器。 The binding engine uses CLR reflection to get the values of the properties. 绑定引擎使用CLR反射来获取属性的值。 Alternatively, objects that implement ICustomTypeDescriptor or have a registered TypeDescriptionProvider also work with the binding engine. 或者,实现ICustomTypeDescriptor或具有已注册TypeDescriptionProvider的对象也可以与绑定引擎一起使用。

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. 有关如何实现可用作绑定源的类的更多信息,请参见本主题后面的为绑定源实现类。

Under the " Other Characteristics " section: 在“ 其他特征 ”部分下:

You cannot bind to public fields. 您不能绑定到公共字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM