[英]Why doesn't RelayCommand RaiseCanExecuteChanged work in a unit test?
[英]RelayCommand Execute delegate doesn't work if local variables are used
我試圖在一個方法中創建一個MVVM Light RelayCommand
:
protected RelayCommand NavigateToViewCommand(string viewName) {
#if false
return new RelayCommand(() => {
Debug.WriteLine("It fired.");
Navigation.Navigate(ServiceLocator.Current.GetInstance<IViewLocator>().GetViewForNavigation("StudentPage2"));
});
#else
return new RelayCommand(() => {
Debug.WriteLine("It fired.");
Navigation.Navigate(ServiceLocator.Current.GetInstance<IViewLocator>().GetViewForNavigation(viewName));
});
#endif
}
如果我將viewName
參數用於RelayCommand
的Execute委托中的RelayCommand
,則不會觸發它。 我將此命令綁定到一個按鈕。 當我單擊該按鈕時,甚至沒有激活Debug.WriteLine
命令(並且放置在它上面的斷點不會中斷)。
但是,如果我更換viewName
用硬編碼字符串,它是一樣的,在值參數viewName
,該RelayCommand
工作正常。
請注意,此代碼(其中未在按鈕中使用該命令)執行時沒有問題:
void Test() {
Command1.Execute(null);
Command2("David").Execute(null);
}
RelayCommand Command1 { get { return new RelayCommand(() => Debug.WriteLine("cmd1 executed.")); } }
RelayCommand Command2(string msg) { return new RelayCommand(() => Debug.WriteLine("cmd2 executed: " + msg)); }
但是如果我將Command2
綁定到Xaml中的Button.Command
,它就不會執行:
public ICommand TestCommand2 { get { return Command2("Cater"); } }
<Button Grid.Row="1" Grid.Column="1" Command="{Binding TestCommand2}" Content="TEST" />
任何想法可能會發生在這里?
UPDATE
進一步的實驗表明,在Execute委托中使用虛擬屬性而不是參數似乎確實有效。 由NavigateToViewCommand
在此代碼中創建的命令在綁定到button.Command時工作正常。 當然,這並不能解決問題; 這只是更多信息。
// In base class:
protected RelayCommand NavigateToViewCommand() {
return new RelayCommand(() => Navigation.Navigate(ServiceLocator.Current.GetInstance<IViewLocator>().GetViewForNavigation(NextPageViewName)));
}
protected virtual string NextPageViewName { get { return string.Empty; } }
// In subclass:
private ICommand m_nextPage;
public ICommand NextPageCommand { get { return m_nextPage ?? (m_nextPage = NavigateToViewCommand()); } }
protected override string NextPageViewName { get { return "StudentPage2"; } }
我更喜歡使用內置的 ICommand
模式而不是將此參數傳遞給RelayCommand
ctor ,這意味着:
protected RelayCommand NavigateToViewCommand()
{
return new RelayCommand((viewName) => {
Debug.WriteLine("It fired.");
Navigation.Navigate(ServiceLocator.Current
.GetInstance<IViewLocator>()
.GetViewForNavigation(viewName.ToString()));
});
}
並像這樣調用execute:
NavigateToViewCommand().Execute("David");
將參數傳遞給命令是一種更溫和的方式。 ps。:我沒試過。 我希望它沒有錯字,而且工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.