2017-09-01 71 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

我編輯了答案,包含我引用的類的最小定義。 –

相關問題