views:

506

answers:

2

Hi everybody,

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.

+1  A: 

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
}
Jobi Joy
No, not really. What I want is to be able to prevent a user from adding two objects with the same value for the property Name. Or at least I should be able to react before allowing the user to persist the change of the Name property.Much like in a datatable based on primary key (unique key for that matter).
Adrian Stoica
+1  A: 

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.
Shimmy