WPF TwoWay绑定自定义与数据提供程序

时间:2014-09-05 15:46:12

标签: c# wpf caching mvvm data-binding

我试图在WPF中使用twoway绑定到自定义数据源(除了支持twoway绑定的db或xml之外),以便在更新源时自动更新UI并在对象时更新源在UI中更改。

我目前拥有一个类CacheObject,它实现了INotifyPropertyChanged和一个自定义(派生)ObservableCollection,CacheWrapper,它订阅缓存中的更改并更新相应的CacheObject,然后自动更新UI。

当我在列表中更新CacheObject时,是否有一种智能方法可以构建到我的CacheWrapper中以更新缓存 - 使用缓存API进行调用。如果我订阅PropertyChanged事件,我将在从代码(从缓存更改)和UI更新对象时收到事件。基本上我想做一件事,如果更新来自源,另一件来自目标。

一些代码示例。

CacheObject

public class CacheObject : INotifyPropertyChanged
{
    private object _key;
    private object _value;

    public event PropertyChangedEventHandler PropertyChanged;

    public CacheObjectViewModel(object key, object value)
    {
        _key = key;
        _value = value;
    }

    public CacheObjectViewModel(KeyValuePair<object, object> keyValuePair)
        : this(keyValuePair.Key, keyValuePair.Value)
    {
    }

    public object Key
    {
        get { return _key; }
        set
        {
            _key = value;
            OnPropertyChanged("Key");
        }
    }

    public object Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnPropertyChanged("Value");
        }
    }

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}

CacheWrapper

public class CacheWrapper : ObservableCollection<CacheObject>, ICacheObserver
{
    private ICache _cache;
    public String Name { get; private set; }

    public CacheWrapepr(string name, ICache cache)
    {
        _cache = cache;
        Name = name;

        cache.AddListener(this);
    }

    public void CacheEntryInserted(CacheEventArgs eventArgs)
    {
        CacheObject cacheObject = eventArgs.NewElement as CacheObject;

        if(cacheObject != null)
        {
            this.Add(cacheObject);
        }
    }

    public void EntryUpdated(CacheEventArgs eventArgs)
    {
        CacheObject cacheObjectNew = eventArgs.NewElement as CacheObject;

        if(cacheObjectNew != null)
        {
            CacheObject cacheObjectExisting = this.FirstOrDefault(x => x.Key == cacheObjectNew.Key);

            if(cacheObjectExisting != null)
            {
                cacheObjectExisting.Value = cacheObjectNew.Value;
            }
        }
    }

    public void EntryDeleted(CacheEventArgs eventArgs)
    {
        CacheObject cacheObject= = eventArgs.OldElement as CacheObject;

        if(cacheObject != null)
        {
            CacheObject cacheObjectExisting = this.FirstOrDefault(x => x.Key == cacheObject.Key);

            if(cacheObjectExisting != null)
            {
                this.Remove(cacheObjectExisting);
            }
        }
    }
}

非常感谢帮助和想法。

0 个答案:

没有答案