NotADba
NotADba

Reputation: 117

Keyed ObservableCollection in Silverlight

I want to implement a keyed observable collection in Silverlight, that will store unique objects based on a property called Name. One way of doing it is to use the ObservableCollectionEx (samples in another stackoverflow post) class which subscribes to all PropertyChanged events on the contained elemens and check to see if the name property changes. Better yet, create my own event that will tell me the name attribute changed and throw a ValidationException if item already exists. I don't necessarily want to retrive the object with an indexer this[Name].

somthing like this:

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

   }
}  

Is there another solution more elegant? Much simpler? Thanks, Adrian

P.S. I know there is also an ObservableDictionary that Dr Wpf put together and it's easy to move it to Silvelight, but I don't know how to use it with DataForm and such.

Upvotes: 0

Views: 2178

Answers (2)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104741

ObservableDictionary(Of TKey, TValue) - VB.NET

General feature list:

  • ObservableDictionary(Of TKey, TValue)
  • AddRange getting notified only once.
  • Generic EventArgs(Of TKey, TValue)
  • NotifyDictionaryChanging(Of TKey, TValue) - a subclass of CancelEventArgs that allows cancelling operation.

Upvotes: 1

Jobi Joy
Jobi Joy

Reputation: 50038

If I am understanding correctly, you need to create a KeyValuePair with propertychanged implementation and use that with 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
}

Upvotes: 2

Related Questions