The following forum(s) have migrated to Microsoft Q&A (Preview): Developing Universal Windows apps!
Visit Microsoft Q&A (Preview) to post new questions.

Learn More

 locked
cannt add element to ObservableCollection and update listbox RRS feed

  • Question

  • Hi, I'm binding my ItemsSource of my ListBox to an ObservableCollection. And now I have an issue, new element isnt added to ObservableCollection. The task is simple, listbox must update when to the collection added new element. I've read a lot of tutorials and they've blown my brain. 

    namespace MWWM
    {
        public class aMan
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string sex { get; set; }
           
        }
    }

    namespace MWWM
    {
       public class view_model : ObservableCollection<aMan>
        {
            public view_model() : base()
            {
                Namelist();
            }
            
            public void Namelist()
            {
                Add(new aMan() { ID = 0, Name = "ded", sex = "M" });
            }
        }
    }

    namespace MWWM
    {
        public partial class MainPage : PhoneApplicationPage
        {
            public MainPage()
            {
                InitializeComponent();
            }
    
            private void add_Man_button_Click(object sender, RoutedEventArgs e)
            {
               var new_man = new aMan() { ID = 0, Name = "rob", sex = "Male" };
               view_model vm = new view_model();
               vm.Add(new_man);
            }   
        }
    }

    Thursday, April 11, 2013 8:22 AM

All replies

  • Hello Alan,

    I see that you are not adding the element to the binded view model, but a new view model you create.

               private void add_Man_button_Click(object sender, RoutedEventArgs e)
            {
               var new_man = new aMan() { ID = 0, Name = "rob", sex = "Male" };
               view_model vm = // Get the already instanced view model, source of your listbox
               vm.Add(new_man);
            }   


    Anyway, I don't think you are using the MVVM pattern correctly, because you are doing in the View operations that should be done in the View Model.
    Thursday, April 11, 2013 9:50 AM
  • Hi Alan,

    There are many issues with your approach, besides what @aZubi mentioned.

    The best way to learn MVVM is to create a project with "Windows Phone Databound App" template. That would create the sample view models implementing INotifyPropertyChanged interface. Modify the MainViewModel and ItemViewModel as needed.

    Even now, after so much working with MVVM, I use these templates as starting point as they reduce lot of coding effort.


    ThanQ...

    Thursday, April 11, 2013 1:05 PM