如何在基本内容页面中使用Reactive的WhenActivated

时间:2018-03-22 14:49:31

标签: xamarin.forms reactiveui

我使用的是反应式内容页面,但如何从基本视图模型中访问某些内容?我是否必须使用实际基本视图模型的对象?

我已经尝试过这样的事情但是因为显而易见的原因,intellisense正在咆哮我。如何访问我添加到基本veiwmodel的命令,我的所有视图模型都扩展了该命令。基本视图模型称为" BaseViewModel"。

另外,你有没有。当你在ContentPageBase和内容页面中激活时,或者这会搞砸什么?

 public class ContentPageBase<TViewModel> : ReactiveContentPage<TViewModel>, IContentPageBase where TViewModel : class
{
    protected IBindingTypeConverter bindingDoubleToIntConverter;
    private Subject<Unit> clearMessageQueueSubject;

    public ContentPageBase() : base()
    {
        clearMessageQueueSubject = new Subject<Unit>();
        bindingDoubleToIntConverter = (IBindingTypeConverter)App.Container.Resolve<IDoubleToIntConverter>();

        this
            .WhenActivated(
                disposables =>
                {       
                   // VS complains when I try to use TViewModel as first param                 
                    clearMessageQueueSubject.InvokeCommand(TViewModel, x => x.ClearMessageQueueCommand).DisposeWith(disposables);
                });
    }

2 个答案:

答案 0 :(得分:1)

根据Diego Rafael Souza的回答,我通过以下方式解决了这个问题:

public class ContentPageBase<TViewModel> : ReactiveContentPage<TViewModel>, IContentPageBase where TViewModel : BaseViewModel
{
    protected IBindingTypeConverter bindingDoubleToIntConverter;
    public Subject<Unit> clearMessageQueueSubject;

    //protected Settings setting;
    public ContentPageBase() : base()
    {
        clearMessageQueueSubject = new Subject<Unit>();
        bindingDoubleToIntConverter = (IBindingTypeConverter)App.Container.Resolve<IDoubleToIntConverter>();


        this
            .WhenActivated(
                disposables =>
                {                        
                    clearMessageQueueSubject.InvokeCommand(this.ViewModel, x => x.ClearMessageQueueCommand).DisposeWith(disposables);
                });
    }

......另一种选择,不一定建议:

public class ContentPageBase<TViewModel> : ReactiveContentPage<TViewModel>, IContentPageBase where TViewModel : class
{
    protected IBindingTypeConverter bindingDoubleToIntConverter;
    public Subject<Unit> clearMessageQueueSubject;

    public ContentPageBase() : base()
    {
        clearMessageQueueSubject = new Subject<Unit>();
        bindingDoubleToIntConverter = (IBindingTypeConverter)App.Container.Resolve<IDoubleToIntConverter>();


        this
            .WhenActivated(
                disposables =>
                {                        
                    clearMessageQueueSubject.InvokeCommand((IBaseViewModel)this.ViewModel, x => x.ClearMessageQueueCommand).DisposeWith(disposables);
                });
    }

答案 1 :(得分:1)

您的约束必须为where TViewModel : BaseViewModel,以便.Net编译器正确识别类型。

也许你需要Invoke方法上的这种类型的实例。