none
Binding to ObservableCollection not working

    Question

  • I have the following code:

     

    <StackPanel>
            <Button Content="Add Value" Command="{Binding AddValue}"/>
            <TextBlock Text="Values:"/>
            <ListBox ItemsSource="{Binding Values}"/>
        </StackPanel>
    

    partial class MainPage
        {
            public MainPage()
            {
                InitializeComponent();
                DataContext = new MainPageViewModel();
            }
        }
    

     

     

    public class MainPageViewModel : INotifyPropertyChanged
        {
            private ObservableCollection<string> _values = new ObservableCollection<string>() { "alpha", "beta", "gamma" };
            public ObservableCollection<string> Values { get { return _values; } }
    
            public event PropertyChangedEventHandler PropertyChanged;
            protected void OnPropertyChanged( string name )
            {
                if( null != PropertyChanged )
                {
                    PropertyChanged( this, new PropertyChangedEventArgs( name ) );
                }
            }
    
            public ICommand AddValue { get; private set; }
    
            public MainPageViewModel()
            {
                AddValue = new RelayCommand( OnExecuteAddValue );
            }
    
            private void OnExecuteAddValue( object context )
            {
                Values.Add( "meow" );
            }
        }
    

     

     

    I can verify that ExecuteAddValue is being called (hits breakpoint) and the Values collection is being updated with additional members, but the binding does not appear to be getting updated.  I remember reading something earlier about ObservableCollection bindings not working and there being a workaround.  Can anyone point me to that post?  


    • Edited by Robert Zhu Tuesday, October 04, 2011 9:38 AM
    Tuesday, October 04, 2011 9:38 AM

Answers

All replies