0

我有一个简单的课程

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;

尽管我仍在寻找一种无需创建新 ViewModel 即可创建 KVC 的通用方法。

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

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));
    }
}
4

0 回答 0