2010-03-09 59 views
1

我一直無法找到任何有關此信息,這似乎是它可能是唯一的方法來解決我SO上的p ast unanswered question。不過,我認爲這應該是一個單獨的問題。可以動態地重新定義ICommand的CanExecute方法嗎?

我想知道是否有一種方法來動態重新定義ICommand派生類的CanExecute方法。我對.NET仍然很陌生,也許這真的很明顯,但我一直無法弄清楚。這裏有人做過這種事嗎?如果我能做到這一點,那對我的特殊問題將非常有用。基本上,我希望能夠遍歷ICommands列表並強制所有的CanExecute方法通過用不同的方法替換它們的實現來返回true。

從搜索「.NET代碼替換」這樣的東西,我發現this article,但我希望有一個稍微簡單的方法。但是,如果我必須這樣做,我會做。

回答

2

讓你的ICommand的派生類中調用的委託,以確定是否CanExecute可以做,這樣你可以公開的委託二傳手並在運行時

改變它作爲一個簡單的例子:

public class MyCommand : ICommand 
{ 
    private Func<object, bool> _canExecuteMethod; 

    public void SetCanExecuteMethod(Func<object, bool> canExecuteMethod) 
    { 
    //check delegate not null if need be 
    _canExecuteMethod = canExecuteMethod; 
    } 

    public bool CanExecute(object parameter) 
    { 
    //check for null delegate - maybe return false if it's null.... 
    return _canExecuteMethod(parameter); 
    } 

    //....other codefor ICommand 

}

如果您不需要額外的數據來做出決定,那麼您也可以僅使用Func<bool>作爲委託。此外,代表可以暴露在其他地方,如果需要,只需從ICommand類調用

+0

謝謝,我認爲這是一個堅實的候選人。我會試一試。 – Dave 2010-03-09 16:00:37