从 XAF 上的嵌套列表视图访问主对象的更简单替代方法

Simpler alternative for accessing master object from nested listview on XAF

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

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

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

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

尚未测试,但您可以使用以下 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;
        }
    }
}

用 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(查看) as IMyObject