2017-09-01 22 views
0

无法从静态上下文访问非静态方法AddNew。为什么不能从静态上下文中引用方法定义?

引用的类:

public class RelayCommand : ICommand 
{ 
    public RelayCommand(Action<object> execute); 
    public RelayCommand(Action execute); 
    public RelayCommand(Action execute, Func<bool> canExecute); 
    public RelayCommand(Action<object> execute, Predicate<object> canExecute); 
    public bool CanExecute(object parameter); 
    public void Execute(object parameter); 
    public event EventHandler CanExecuteChanged; 
} 

    [TypeForwardedFrom("PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")] 
    [TypeConverter("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")] 
    [ValueSerializer("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")] 
    public interface ICommand 
    { 
    /// <summary>Defines the method that determines whether the command can execute in its current state.</summary> 
    /// <returns>true if this command can be executed; otherwise, false.</returns> 
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> 
    bool CanExecute(object parameter); 
    /// <summary>Defines the method to be called when the command is invoked.</summary> 
    /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> 
    void Execute(object parameter); 
    /// <summary>Occurs when changes occur that affect whether or not the command should execute.</summary> 
    event EventHandler CanExecuteChanged; 
    } 

我的代码:

public class ExampleViewModel: NotificationObject 
{ 

    public ICommand AddNewCommand { get; } = new Microsoft.Practices.Prism.Commands.DelegateCommand(AddNew, CanAdd); // method references arn't static?? 

    public String NewName { get; set; } = ""; 

    internal bool CanAdd() 
    { 
     //Can Add if string is non empty & non null 
     return !string.IsNullOrEmpty(NewName); 
    } 

    internal void AddNew() 
    { 
     var name = NewName ?? "NeedToCheckforNull"; 

     var newWindSpeedEnv = new WindSpeedEnvelope() 
     { 
      Id = Guid.NewGuid(), 
      Name = name 
     }; 
    } 
} 

从Java的到来,我本来期望这个工作,因为这些方法是众所周知的,在编译时静态存在吗?

回答

1

只是初始化DelegateCommand在ExampleViewModel构造:

public ExampleViewModel() 
{ 
    AddNewCommand = new DelegateCommand(AddNew, CanAdd); 
} 

public ICommand AddNewCommand { get; private set; } 

作为一个侧面说明,NewName永远不会计算为NULL因为你给它的string.Empty的值,所以空合并运算符不在那里做任何事。

+0

请注意,本节中的代码仍然非常流行,因为我从那些试图学习和清理东西的地方的老班复制。 我知道,如果我将它填充到构造函数中而不是作为一个自动属性初始值设定项,它应该可以正常工作? –

+0

应该这样做,我会自己验证它,但棱镜的下载大小是可怕的:-) –

+0

我编辑了答案,包含我引用的类的最小定义。 –

相关问题