BindableDynamicDictionary
///
/// Bindable dynamic dictionary.
///
public sealed class BindableDynamicDictionary : DynamicObject, INotifyPropertyChanged
{
///
/// The internal dictionary.
///
private readonly Dictionary _dictionary;
///
/// Creates a new BindableDynamicDictionary with an empty internal dictionary.
///
public BindableDynamicDictionary()
{
_dictionary = new Dictionary();
}
///
/// Copies the contents of the given dictionary to initilize the internal dictionary.
///
///
public BindableDynamicDictionary(IDictionary source)
{
_dictionary = new Dictionary(source);
}
///
/// You can still use this as a dictionary.
///
///
///
public object this[string key]
{
get
{
return _dictionary[key];
}
set
{
_dictionary[key] = value;
RaisePropertyChanged(key);
}
}
///
/// This allows you to get properties dynamically.
///
///
///
///
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _dictionary.TryGetValue(binder.Name, out result);
}
///
/// This allows you to set properties dynamically.
///
///
///
///
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_dictionary[binder.Name] = value;
RaisePropertyChanged(binder.Name);
return true;
}
///
/// This is used to list the current dynamic members.
///
///
public override IEnumerable GetDynamicMemberNames()
{
return _dictionary.Keys;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
var propChange = PropertyChanged;
if (propChange == null) return;
propChange(this, new PropertyChangedEventArgs(propertyName));
}
}
|