2014-01-28 17 views
2

我正在使用ReactiveUI及其路由器。ReactiveUI,瀏覽時從視圖模型獲取列表 - 如果視圖模型實現接口

我的一些IRoutableViewModel S的實現接口IHaveCommands,其中有一個屬性IEnumerable<IReactiveCommand> Commands { get; }

所以,我想要的東西,是當前視圖模型的命令列表中我IScreen實現中,AppBootstrapper

什麼是'正確'的方式來實現呢?

我都有點懂了用下面的代碼工作,但我的膽量告訴我,還有其他的,這樣做的更好的辦法....

public class AppBootstrapper : ReactiveObject, IScreen 
{ 
    public IRoutingState Router { get; private set; } 

    public AppBootstrapper(IMutableDependencyResolver dependencyResolver = null, IRoutingState testRouter = null) 
    { 
     Router = testRouter ?? new RoutingState(); 

     Router.CurrentViewModel.Where(x => x != null) 
       .Select(x => typeof(IHaveCommands).IsAssignableFrom(x.GetType()) ? ((IHaveCommands)x).Commands : null) 
       .ToProperty(this, x => x.Commands, out _toolbarCommands); 

     ... 
    } 

    readonly ObservableAsPropertyHelper<IEnumerable<CommandSpec>> _toolbarCommands; 
    public IEnumerable<CommandSpec> ToolbarCommands { get { return _toolbarCommands.Value; } } 

} 

任何提示嗎?

回答

2

這對我來說很好!除了一些可能的小可讀性修正之外,這是您應該做的事情™。這是一個稍微更清潔的版本:

Router.CurrentViewModel 
    .Select(x => { 
     var haveCmds = x as IHaveCommands; 
     return haveCmds != null ? haveCmds.Commands : null; 
    }) 
    .ToProperty(this, x => x.Commands, out _toolbarCommands); 
+0

太棒了!也許我開始得到這個東西:-) – Vegar