【问题标题】:Keyed ObservableCollection in SilverlightSilverlight 中的键控 ObservableCollection
【发布时间】:2010-11-30 06:49:04
【问题描述】:

我想在 Silverlight 中实现一个键控 observable 集合,它将基于名为 Name 的属性存储唯一对象。一种方法是使用 ObservableCollectionEx(另一个 stackoverflow 帖子中的示例)类订阅包含的元素上的所有 PropertyChanged 事件,并检查 name 属性是否更改。更好的是,创建我自己的事件,它会告诉我 name 属性已更改,如果 item 已存在则抛出 ValidationException。我不一定想用索引器 this[Name] 检索对象。

类似这样的:

private string name;  
public string Name  
{  
   get { return name; }  
   set {
         if (value != name)
         {  
              OnNameChanged();  
              name = value;   
              OnPropertyChanged("Name");  
         }

   }
}  

还有其他更优雅的解决方案吗?简单得多? 谢谢, 阿德里安

附:我知道 Wpf 博士还整理了一个 ObservableDictionary,很容易将其移至 Silvelight,但我不知道如何将它与 DataForm 等一起使用。

【问题讨论】:

    标签: silverlight observablecollection keyedcollection


    【解决方案1】:

    如果我理解正确,您需要创建一个具有 propertychanged 实现的 KeyValuePair 并将其与 ObservableCollection 一起使用

    ObservableCollection< KeyValuePair<string,string>> 
    
    public class KeyValuePair<TKey, TValue> : INotifyPropertyChanged
    {
        public KeyValuePair(TKey key, TValue value)
        {
            _key = key;
            _value = value;
        }
    
        public TKey Key  { get {  return _key; } }
    
        public TValue Value { get  { return _value; }
            set
            {
                _value = value;
                NotifyPropertyChanged("Value");
            }
        }
    
    
        private TKey _key;
        private TValue _value;
    
        #region INotifyPropertyChanged Members
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
    

    【讨论】:

    • 不,不是。我想要的是能够防止用户为属性名称添加具有相同值的两个对象。或者至少我应该能够在允许用户持久更改 Name 属性之前做出反应。就像在基于主键(唯一键)的数据表中一样。
    【解决方案2】:

    ObservableDictionary(Of TKey, TValue) - VB.NET

    一般功能列表:

    • ObservableDictionary(Of TKey, TValue)
    • AddRange 只收到一次通知。
    • 通用 EventArgs(Of TKey, TValue)
    • NotifyDictionaryChanging(Of TKey, TValue) - CancelEventArgs 的子类,允许取消操作。

    【讨论】:

    • 除非它没有实现 INotifyCollectionChanged。似乎需要绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 1970-01-01
    • 2020-06-21
    相关资源
    最近更新 更多