2011-08-21 29 views
0

我正在研究我的第一個大型WPF MVVM應用程序,它將MVVM Light Toolkit與Josh Smith的RelayCommand結合使用。 我遇到的問題是我將此命令綁定到ContextMenu中的一個項目,該項目始終處於禁用狀態。爲什麼綁定到RelayCommand的ContextMenu項總是被禁用?

這裏的菜單項的代碼片段:

<MenuItem 
    Header="Verwijderen" 
    Command="{StaticResource DeleteNoteCommandReference}" 
    CommandParameter="{Binding}" /> 

現在我已經與做的CommandBinding是這樣的:我使用了一種叫做CommandReference類,我發現here

這是commandreference本身:

<command:CommandReference 
    x:Key="DeleteNoteCommandReference" 
    Command="{Binding DeleteNoteCommand}" /> 

爲什麼我這樣做是因爲問題上的CommandBinding一個ContextMenu,我注意到(所造成的事實,即一個ContextMenu不是的部分原因邏輯/可視化樹)。我在網上發現了關於這個主題的幾個主題,其中一些發現了CommandReference類,這似乎是我的問題的一個很好的解決方案。 這些命令綁定問題確實消失了,但看起來我的命令CanExecute無法識別,或者因爲MenuItem保持禁用狀態。

在視圖模型(這勢必將視圖作爲其DataContext的),我該命令的如下代碼:

/// <summary> 
    /// Command for deleting a note. 
    /// </summary> 
    public RelayCommand<NoteViewModel> DeleteNoteCommand { 
     get; 
     private set; 
    } 

    /// <summary> 
    /// CanExecute method for the DeleteNoteCommand. 
    /// </summary> 
    /// <param name="note">The NoteViewModel that CanExecute needs to check.</param> 
    /// <returns>True if the note can be deleted, false otherwise.</returns> 
    public bool DeleteNoteCommandCanExecute(NoteViewModel note) { 
     return Notes.Contains(note); 
    } 

    /// <summary> 
    /// Creates all commands for this ViewModel. 
    /// </summary> 
    private void CreateCommands() { 
     DeleteNoteCommand = new RelayCommand<NoteViewModel>(param => DeleteNote(param), param => DeleteNoteCommandCanExecute(param)); 
    } 

缺少什麼我在這裏把我的代碼的功能? 我認爲它可能與我正在使用的CommandReference有關,但我不知道要尋找什麼。

真的希望你們能幫忙!

回答

0

嘗試設置的DeleteNoteCommandCanExecute和檢查中的斷點:

  1. 如果它被打開上下文菜單,並
  2. DeleteNoteCommandCanExecute代碼不會拋出異常之前調用(例如:note參數爲空)

在第一種情況下,如果沒有被調用它,嘗試呼籲CommandManagerInvalidateRequerySuggested方法強制的重新查詢方法。

祝你好運!

+0

感謝您的建議,但並沒有調用斷點......我在其他地方瞭解了這個InvalidateRequerySuggested方法,但我應該在哪裏調用它?在構建我的視圖時? – Thomas

+0

理論上你應該在條件改變或可能改變時調用它。 (The Notes.Contains(note))。 – aKzenT

+1

對於Bug跟蹤,請嘗試將它放在不同的地方(例如,當上下文菜單彈出時),看看它是否有所作爲。但我認爲你的問題是命令參數,因爲你正在使用綁定,但上下文菜單不是可視化樹的一部分。奇怪的是,斷點從來沒有被打... – aKzenT

相關問題