WPF应用程序中的自定义视图演示者

时间:2018-08-01 21:53:14

标签: mvvmcross

我正在用MvvmCross编写WPF应用程序。我想要一个自定义视图演示者。这是我写的:

public class ViewPresenter : MvxWpfViewPresenter
{
    ContentControl _contentControl;

    FrameworkElement _currentContentView;
    FrameworkElement _rootContentView;

    public ViewPresenter(ContentControl c)
    {
        _contentControl = c;

        AddPresentationHintHandler<SetRootHint>(SetRootHintHandler);
        AddPresentationHintHandler<PopToRootHint>(PopToRootHintHandler);
    }

    protected override void ShowContentView(FrameworkElement element, MvxContentPresentationAttribute attribute, MvxViewModelRequest request)
    {
        base.ShowContentView(element, attribute, request);

        _currentContentView = element;
    }

    private bool SetRootHintHandler(SetRootHint hint)
    {
        _rootContentView = _currentContentView;

        return true;
    }

    private bool PopToRootHintHandler(PopToRootHint hint)
    {

        return true;
    }
}

我正在Setup类中注册它:

public class Setup : MvxWpfSetup<Core.App>
{
    protected override IMvxWpfViewPresenter CreateViewPresenter(ContentControl root)
    {
        return new ViewPresenter(root);
    }
}

当我尝试显示我的第一个视图时,它在此行崩溃:

base.ShowContentView(element, attribute, request);

显示消息:

  

System.InvalidOperationException:'序列不包含任何元素'

如果我没有改写ShowContentView,它仍然会崩溃。而且,如果我不打电话给base.ShowContentView(element, attribute, request),它也不会显示我的视图。

编辑

在我的Visual Studio环境中启用Common Language Runtime Exceptions后,我可以看到异常实际上来自mscorlib.dll,并要求AsyncMethodBuilder.cs查看调用堆栈帧的源。引发异常。我所有的nuget程序包都是最新的,并且在Windows 10上运行。我相信从Windows 10开始不赞成使用WPF。我的WPF项目针对.NET 4.7.2,而我的Core项目针对.NET Standard 2.0。但是我仍然不知道该如何解决。.我也使用最新的MvvmCross(6.1.2.0)。

编辑2

我制作了一个带有相同问题的小型示例应用程序:

https://drive.google.com/file/d/1uROc8TYzWdx54BV8LtgCNLtwhc_MhXq3/view?usp=sharing

1 个答案:

答案 0 :(得分:1)

感谢您的样品。我能够弄清楚。

由于没有在base上调用ViewPresenter构造函数,因此遇到了此问题。将您的ViewPresenter代码更改为此:

public ViewPresenter(ContentControl c) : base(c)
{
    _contentControl = c;

    AddPresentationHintHandler<SetRootHint>(SetRootHintHandler);
    AddPresentationHintHandler<PopToRootHint>(PopToRootHintHandler);
}

这样,base constructor将被调用,ContentControl将被添加到_frameworkElementsDictionary,而不会抛出异常

  

序列不包含任何元素

'因为其中将包含一个元素

相关问题