Bind observable dictionary
I wrote a little observable dictionary and I want to bind it to a ComboBox and a ListBox.
Indeed, it does not work and I do not know why.
This is my ObservableDictionary wrapper class (I did some experiments and raised some events in Add()):
public class ObservableDictionary<TKey, TValue> : INotifyPropertyChanged, INotifyCollectionChanged, IDictionary<TKey, TValue>
{
private Dictionary<TKey, TValue> _dic = new Dictionary<TKey, TValue>();
public event PropertyChangedEventHandler PropertyChanged;
public event NotifyCollectionChangedEventHandler CollectionChanged;
private void OnCollectionChanged( object sender, NotifyCollectionChangedAction action, object value )
{
if (CollectionChanged != null)
{
CollectionChanged( sender, new NotifyCollectionChangedEventArgs( action, value ) );
}
}
private void OnPropertyChanged( object sender, string propertyName )
{
if (PropertyChanged != null)
{
PropertyChanged( this, new PropertyChangedEventArgs( propertyName ) );
}
}
#region IDictionary<TKey,TValue> Members
public void Add( TKey key, TValue value )
{
_dic.Add( key, value );
OnCollectionChanged( this, NotifyCollectionChangedAction.Add, new KeyValuePair<TKey, TValue>(key, value) );
OnPropertyChanged( this, "Values" );
OnPropertyChanged( this, "Keys" );
OnPropertyChanged( this, "Count" );
}
...
}
My Window class:
public partial class Window1 : System.Windows.Window
{
private ObservableDictionary<string, string> _layer = new ObservableDictionary<string, string>();
// save number of insertion
private int count = 0;
public Window1()
{
InitializeComponent();
}
private void OnWindowLoaded( object sender, RoutedEventArgs args )
{
// Binding configuration
Binding binding = new Binding();
binding.Source = _layer;
//binding.Path = new PropertyPath("Values" ); <-- does not work
binding.Mode = BindingMode.OneWay;
binding.NotifyOnTargetUpdated = true;
binding.NotifyOnSourceUpdated = true;
// Set binding for ComboBox
_comboBox.SetBinding( ComboBox.ItemsSourceProperty, binding );
_listBox.SetBinding( ListBox.ItemsSourceProperty, binding );
//_listBox.ItemsSource = _layer;
private void InsertLayer( object sender, RoutedEventArgs args )
{
// Insert values in observable collection again
try
{
_layer.Add( count.ToString(), "layer_" + count.ToString() );
count++;
}
catch (Exception e)
{
Debug.WriteLine( e.Message );
}
}
}
However, I get the collection of the dictionary and [0, layer0], [1, layer1], etc is shown, but I want to display the value only.
Can somebody help me? Setting Binding.Path to "Values" did not help.
One more question: What is the difference between SetBinding(ItemsSourceProperty, Binding) and setting the property IntemsSource?
Thanks a lot,
Alex

