2

我想知道除此之外是否有简单明了的方法可以从嵌套的列表视图控制器访问主对象。

((PropertyCollectionSource)((ListView)View).CollectionSource).MasterObject

我是否必须在需要访问主对象的任何地方写这个?

我认为这不是一种优雅的方式,而且看起来很蹩脚。

4

2 回答 2

3

尚未测试,但您可以使用以下 ViewController 后代:

public class NestedViewController : ViewController
{
    protected PropertyCollectionSource PropertyCollectionSource
    {
        get
        {
            return View is ListView ? ((ListView)View).CollectionSource is PropertyCollectionSource ? ((ListView)View).CollectionSource as PropertyCollectionSource : null : null;
        }
    }

    protected object MasterObject
    {
        get
        {
            return PropertyCollectionSource != null ? PropertyCollectionSource.MasterObject : null;
        }
    }
}
于 2015-06-11T13:31:28.573 回答
1

用 C#6 简化上述答案

public partial class NestedViewController : ViewController
{
    protected PropertyCollectionSource PropertyCollectionSource => (View as ListView)?.CollectionSource as PropertyCollectionSource;

    protected object MasterObject => PropertyCollectionSource?.MasterObject;
}

我也把它移到了一个函数中

public static class HandyControllerFunctions
{
    public static object GetMasterObject(View view)
    {
        var propertyCollectionSource = (view as ListView)?.CollectionSource as PropertyCollectionSource;
        return propertyCollectionSource?.MasterObject ;
    }
}

并称之为例如

var myObject = HandyControllerFunctions.GetMasterObject(View) as IMyObject

于 2017-01-16T21:26:46.483 回答