如何将一个简单的类转换为KVC以绑定到CollectionViewItem

时间:2013-09-26 08:03:55

标签: mvvmcross monomac

我有一个简单的课程

public class Colora
{
    public Colora()
    {
        Created = DateTime.Now;
    }

    public string Name { get; set; }
    public DateTime Created { get; set; }
}

需要保持简单(它在PCL中)。如何将其转换为符合KVC标准的NSObject,以便它可以在CollectionView中显示?

我在想像

这样的东西
        List<Colora> coloras = new List<Colora> () {
            new Colora() { Name = "Red" },
            new Colora() { Name = "Blue" }
        };
        var objs = new NSObject[coloras.Count];
        for (int i = 0; i < coloras.Count; i++) {
            objs [i] = NSObject.FromObject (coloras [i]);
        }       
        devCollectionView.Content = objs;

但是FromObject不适用于我的班级。在这种情况下,数组不必是可变的。

更新。值得注意的是,这可行

public class ColoraViewModel : NSObject
{
    private readonly Colora _colora;
    public ColoraViewModel (Colora colora)
    {
        _colora = colora;
    }

    [Export("name")]
    public string Name {
        get { return _colora.Name; }
        set {
            if (_colora.Name != value) {
                _colora.Name = value;
            }
        }
    }
}

        List<Colora> coloras = new List<Colora> () {
            new Colora() { Name = "Red" },
            new Colora() { Name = "Blue" }
        };
        var objs = new NSObject[coloras.Count];
        for (int i = 0; i < coloras.Count; i++) {
            objs [i] = new ColoraViewModel (coloras [i]);
        }       
        devCollectionView.Content = objs;

虽然我仍在寻找创建KVC的一般方法,而无需制作新的ViewModel。

这不起作用,但我梦想有这样的事情:

public class KVCObject : NSObject
{
    private readonly object _t;
    private readonly Type _type;


    public KVCObject (object t)
    {
        _t = t;
        _type = t.GetType();
    }

    public override void SetValueForKey (NSObject value, NSString key)
    {
        var info = _type.GetProperty (key.ToString ());
        info.SetValue (_t, value);
    }

    public override NSObject ValueForKey (NSString key)
    {
        var info = _type.GetProperty (key.ToString ());
        return NSObject.FromObject(info.GetValue (_t));
    }
}

0 个答案:

没有答案