Code Example of ObservableCollection<T> NOT in code behind (MVVM)


  • I am needing to see an example of creating and binding an ObservableCollection in an MVVM model.  No code behind. I want to be able to create an ObservableCollection that will hold data input from a textbox and have it's elements bound to a listbox in the GUI.
    Thursday, July 03, 2014 9:19 PM


  • Just bind the ListBox's ItemsSource property to a view model property of type ObservableCollection<T>:

    class ViewModel
            public ViewModel()
                this.MyCollection = new ObservableCollection<string>();
            public ObservableCollection<string> MyCollection { get; set; }

    <Window x:Class="WpfApplication36.MainWindow"
            Title="MainWindow" Height="350" Width="525">
            <ListBox ItemsSource="{Binding MyCollection}"></ListBox>

    You can then add an item to the ObservableCollection at runtime and the ListView will display the newly added item automatically.

    Regarding the TextBox, you will have to more specific. You could bind the TextBox's Text property to a string property of the view model and then access this value from anywhere in the view model.

    Please refer to the following article for more information about how to implement the MVVM pattern in WPF applications:

    • Marked as answer by MootchMonster Tuesday, July 08, 2014 1:12 PM
    Thursday, July 03, 2014 9:44 PM